home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / perl5 / Log / Log4perl.pm
Encoding:
Perl POD Document  |  2010-07-21  |  96.5 KB  |  2,784 lines

  1. ##################################################
  2. package Log::Log4perl;
  3. ##################################################
  4.  
  5. END { local($?); Log::Log4perl::Logger::cleanup(); }
  6.  
  7. use 5.006;
  8. use strict;
  9. use warnings;
  10.  
  11. use Log::Log4perl::Util;
  12. use Log::Log4perl::Logger;
  13. use Log::Log4perl::Level;
  14. use Log::Log4perl::Config;
  15. use Log::Log4perl::Appender;
  16.  
  17. our $VERSION = '1.29';
  18.  
  19.    # set this to '1' if you're using a wrapper
  20.    # around Log::Log4perl
  21. our $caller_depth = 0;
  22.  
  23.     #this is a mapping of convenience names to opcode masks used in
  24.     #$ALLOWED_CODE_OPS_IN_CONFIG_FILE below
  25. our %ALLOWED_CODE_OPS = (
  26.     'safe'        => [ ':browse' ],
  27.     'restrictive' => [ ':default' ],
  28. );
  29.  
  30. our %WRAPPERS_REGISTERED = map { $_ => 1 } qw(Log::Log4perl);
  31.  
  32.     #set this to the opcodes which are allowed when
  33.     #$ALLOW_CODE_IN_CONFIG_FILE is set to a true value
  34.     #if undefined, there are no restrictions on code that can be
  35.     #excuted
  36. our @ALLOWED_CODE_OPS_IN_CONFIG_FILE;
  37.  
  38.     #this hash lists things that should be exported into the Safe
  39.     #compartment.  The keys are the package the symbol should be
  40.     #exported from and the values are array references to the names
  41.     #of the symbols (including the leading type specifier)
  42. our %VARS_SHARED_WITH_SAFE_COMPARTMENT = (
  43.     main => [ '%ENV' ],
  44. );
  45.  
  46.     #setting this to a true value will allow Perl code to be executed
  47.     #within the config file.  It works in conjunction with
  48.     #$ALLOWED_CODE_OPS_IN_CONFIG_FILE, which if defined restricts the
  49.     #opcodes which can be executed using the 'Safe' module.
  50.     #setting this to a false value disables code execution in the
  51.     #config file
  52. our $ALLOW_CODE_IN_CONFIG_FILE = 1;
  53.  
  54.     #arrays in a log message will be joined using this character,
  55.     #see Log::Log4perl::Appender::DBI
  56. our $JOIN_MSG_ARRAY_CHAR = '';
  57.  
  58.     #version required for XML::DOM, to enable XML Config parsing
  59.     #and XML Config unit tests
  60. our $DOM_VERSION_REQUIRED = '1.29'; 
  61.  
  62. our $CHATTY_DESTROY_METHODS = 0;
  63.  
  64. our $LOGDIE_MESSAGE_ON_STDERR = 1;
  65. our $LOGEXIT_CODE             = 1;
  66. our %IMPORT_CALLED;
  67.  
  68. ##################################################
  69. sub import {
  70. ##################################################
  71.     my($class) = shift;
  72.  
  73.     no strict qw(refs);
  74.  
  75.     my $caller_pkg = caller();
  76.  
  77.     return 1 if $IMPORT_CALLED{$caller_pkg}++;
  78.  
  79.     my(%tags) = map { $_ => 1 } @_;
  80.  
  81.         # Lazy man's logger
  82.     if(exists $tags{':easy'}) {
  83.         $tags{':levels'} = 1;
  84.         $tags{':nowarn'} = 1;
  85.         $tags{'get_logger'} = 1;
  86.     }
  87.  
  88.     if(exists $tags{':no_extra_logdie_message'}) {
  89.         $Log::Log4perl::LOGDIE_MESSAGE_ON_STDERR = 0;
  90.         delete $tags{':no_extra_logdie_message'};
  91.     }
  92.  
  93.     if(exists $tags{get_logger}) {
  94.         # Export get_logger into the calling module's 
  95.  
  96.         *{"$caller_pkg\::get_logger"} = *get_logger;
  97.  
  98.         delete $tags{get_logger};
  99.     }
  100.  
  101.     if(exists $tags{':levels'}) {
  102.         # Export log levels ($DEBUG, $INFO etc.) from Log4perl::Level
  103.         for my $key (keys %Log::Log4perl::Level::PRIORITY) {
  104.             my $name  = "$caller_pkg\::$key";
  105.                # Need to split this up in two lines, or CVS will
  106.                # mess it up.
  107.             my $value = $
  108.                         Log::Log4perl::Level::PRIORITY{$key};
  109.             *{"$name"} = \$value;
  110.         }
  111.  
  112.         delete $tags{':levels'};
  113.     }
  114.  
  115.         # Lazy man's logger
  116.     if(exists $tags{':easy'}) {
  117.         delete $tags{':easy'};
  118.  
  119.             # Define default logger object in caller's package
  120.         my $logger = get_logger("$caller_pkg");
  121.         ${$caller_pkg . '::_default_logger'} = $logger;
  122.         
  123.             # Define DEBUG, INFO, etc. routines in caller's package
  124.         for(qw(TRACE DEBUG INFO WARN ERROR FATAL ALWAYS)) {
  125.             my $level   = $_;
  126.             $level = "OFF" if $level eq "ALWAYS";
  127.             my $lclevel = lc($_);
  128.             *{"$caller_pkg\::$_"} = sub { 
  129.                 Log::Log4perl::Logger::init_warn() unless 
  130.                     $Log::Log4perl::Logger::INITIALIZED or
  131.                     $Log::Log4perl::Logger::NON_INIT_WARNED;
  132.                 $logger->{$level}->($logger, @_, $level);
  133.             };
  134.         }
  135.  
  136.             # Define LOGCROAK, LOGCLUCK, etc. routines in caller's package
  137.         for(qw(LOGCROAK LOGCLUCK LOGCARP LOGCONFESS)) {
  138.             my $method = "Log::Log4perl::Logger::" . lc($_);
  139.  
  140.             *{"$caller_pkg\::$_"} = sub {
  141.                 unshift @_, $logger;
  142.                 goto &$method;
  143.             };
  144.         }
  145.  
  146.             # Define LOGDIE, LOGWARN
  147.  
  148.         *{"$caller_pkg\::LOGDIE"} = sub {
  149.             Log::Log4perl::Logger::init_warn() unless 
  150.                     $Log::Log4perl::Logger::INITIALIZED or
  151.                     $Log::Log4perl::Logger::NON_INIT_WARNED;
  152.             $logger->{FATAL}->($logger, @_, "FATAL");
  153.             $Log::Log4perl::LOGDIE_MESSAGE_ON_STDERR ?
  154.                 CORE::die(Log::Log4perl::Logger::callerline(join '', @_)) :
  155.                 exit $Log::Log4perl::LOGEXIT_CODE;
  156.         };
  157.  
  158.         *{"$caller_pkg\::LOGEXIT"} = sub {
  159.             Log::Log4perl::Logger::init_warn() unless 
  160.                     $Log::Log4perl::Logger::INITIALIZED or
  161.                     $Log::Log4perl::Logger::NON_INIT_WARNED;
  162.             $logger->{FATAL}->($logger, @_, "FATAL");
  163.             exit $Log::Log4perl::LOGEXIT_CODE;
  164.         };
  165.  
  166.         *{"$caller_pkg\::LOGWARN"} = sub { 
  167.             Log::Log4perl::Logger::init_warn() unless 
  168.                     $Log::Log4perl::Logger::INITIALIZED or
  169.                     $Log::Log4perl::Logger::NON_INIT_WARNED;
  170.             $logger->{WARN}->($logger, @_, "WARN");
  171.             $Log::Log4perl::LOGDIE_MESSAGE_ON_STDERR ?
  172.             CORE::warn(Log::Log4perl::Logger::callerline(join '', @_)) :
  173.             exit $Log::Log4perl::LOGEXIT_CODE;
  174.         };
  175.     }
  176.  
  177.     if(exists $tags{':nowarn'}) {
  178.         $Log::Log4perl::Logger::NON_INIT_WARNED = 1;
  179.         delete $tags{':nowarn'};
  180.     }
  181.  
  182.     if(exists $tags{':nostrict'}) {
  183.         $Log::Log4perl::Logger::NO_STRICT = 1;
  184.         delete $tags{':nostrict'};
  185.     }
  186.  
  187.     if(exists $tags{':resurrect'}) {
  188.         my $FILTER_MODULE = "Filter::Util::Call";
  189.         if(! Log::Log4perl::Util::module_available($FILTER_MODULE)) {
  190.             die "$FILTER_MODULE required with :resurrect" .
  191.                 "(install from CPAN)";
  192.         }
  193.         eval "require $FILTER_MODULE" or die "Cannot pull in $FILTER_MODULE";
  194.         Filter::Util::Call::filter_add(
  195.             sub {
  196.                 my($status);
  197.                 s/^\s*###l4p// if
  198.                     ($status = Filter::Util::Call::filter_read()) > 0;
  199.                 $status;
  200.                 });
  201.         delete $tags{':resurrect'};
  202.     }
  203.  
  204.     if(keys %tags) {
  205.         # We received an Option we couldn't understand.
  206.         die "Unknown Option(s): @{[keys %tags]}";
  207.     }
  208. }
  209.  
  210. ##################################################
  211. sub initialized {
  212. ##################################################
  213.     return $Log::Log4perl::Logger::INITIALIZED;
  214. }
  215.  
  216. ##################################################
  217. sub new {
  218. ##################################################
  219.     die "THIS CLASS ISN'T FOR DIRECT USE. " .
  220.         "PLEASE CHECK 'perldoc " . __PACKAGE__ . "'.";
  221. }
  222.  
  223. ##################################################
  224. sub reset { # Mainly for debugging/testing
  225. ##################################################
  226.     # Delegate this to the logger ...
  227.     return Log::Log4perl::Logger->reset();
  228. }
  229.  
  230. ##################################################
  231. sub init_once { # Call init only if it hasn't been
  232.                 # called yet.
  233. ##################################################
  234.     init(@_) unless $Log::Log4perl::Logger::INITIALIZED;
  235. }
  236.  
  237. ##################################################
  238. sub init { # Read the config file
  239. ##################################################
  240.     my($class, @args) = @_;
  241.  
  242.     #woops, they called ::init instead of ->init, let's be forgiving
  243.     if ($class ne __PACKAGE__) {
  244.         unshift(@args, $class);
  245.     }
  246.  
  247.     # Delegate this to the config module
  248.     return Log::Log4perl::Config->init(@args);
  249. }
  250.  
  251. ##################################################
  252. sub init_and_watch { 
  253. ##################################################
  254.     my($class, @args) = @_;
  255.  
  256.     #woops, they called ::init instead of ->init, let's be forgiving
  257.     if ($class ne __PACKAGE__) {
  258.         unshift(@args, $class);
  259.     }
  260.  
  261.     # Delegate this to the config module
  262.     return Log::Log4perl::Config->init_and_watch(@args);
  263. }
  264.  
  265.  
  266. ##################################################
  267. sub easy_init { # Initialize the root logger with a screen appender
  268. ##################################################
  269.     my($class, @args) = @_;
  270.  
  271.     # Did somebody call us with Log::Log4perl::easy_init()?
  272.     if(ref($class) or $class =~ /^\d+$/) {
  273.         unshift @args, $class;
  274.     }
  275.  
  276.     # Reset everything first
  277.     Log::Log4perl->reset();
  278.  
  279.     my @loggers = ();
  280.  
  281.     my %default = ( level    => $DEBUG,
  282.                     file     => "STDERR",
  283.                     utf8     => undef,
  284.                     category => "",
  285.                     layout   => "%d %m%n",
  286.                   );
  287.  
  288.     if(!@args) {
  289.         push @loggers, \%default;
  290.     } else {
  291.         for my $arg (@args) {
  292.             if($arg =~ /^\d+$/) {
  293.                 my %logger = (%default, level => $arg);
  294.                 push @loggers, \%logger;
  295.             } elsif(ref($arg) eq "HASH") {
  296.                 my %logger = (%default, %$arg);
  297.                 push @loggers, \%logger;
  298.             }
  299.         }
  300.     }
  301.  
  302.     for my $logger (@loggers) {
  303.  
  304.         my $app;
  305.  
  306.         if($logger->{file} =~ /^stderr$/i) {
  307.             $app = Log::Log4perl::Appender->new(
  308.                 "Log::Log4perl::Appender::Screen",
  309.                 utf8 => $logger->{utf8});
  310.         } elsif($logger->{file} =~ /^stdout$/i) {
  311.             $app = Log::Log4perl::Appender->new(
  312.                 "Log::Log4perl::Appender::Screen",
  313.                 stderr => 0,
  314.                 utf8   => $logger->{utf8});
  315.         } else {
  316.             my $binmode;
  317.             if($logger->{file} =~ s/^(:.*?)>/>/) {
  318.                 $binmode = $1;
  319.             }
  320.             $logger->{file} =~ /^(>)?(>)?/;
  321.             my $mode = ($2 ? "append" : "write");
  322.             $logger->{file} =~ s/.*>+\s*//g;
  323.             $app = Log::Log4perl::Appender->new(
  324.                 "Log::Log4perl::Appender::File",
  325.                 filename => $logger->{file},
  326.                 mode     => $mode,
  327.                 utf8     => $logger->{utf8},
  328.                 binmode  => $binmode,
  329.             );
  330.         }
  331.  
  332.         my $layout = Log::Log4perl::Layout::PatternLayout->new(
  333.                                                         $logger->{layout});
  334.         $app->layout($layout);
  335.  
  336.         my $log = Log::Log4perl->get_logger($logger->{category});
  337.         $log->level($logger->{level});
  338.         $log->add_appender($app);
  339.     }
  340.  
  341.     $Log::Log4perl::Logger::INITIALIZED = 1;
  342. }
  343.  
  344. ##################################################
  345. sub wrapper_register {  
  346. ##################################################
  347.     my $wrapper = $_[-1];
  348.  
  349.     $WRAPPERS_REGISTERED{ $wrapper } = 1;
  350. }
  351.  
  352. ##################################################
  353. sub get_logger {  # Get an instance (shortcut)
  354. ##################################################
  355.     # get_logger() can be called in the following ways:
  356.     #
  357.     #   (1) Log::Log4perl::get_logger()     => ()
  358.     #   (2) Log::Log4perl->get_logger()     => ("Log::Log4perl")
  359.     #   (3) Log::Log4perl::get_logger($cat) => ($cat)
  360.     #   
  361.     #   (5) Log::Log4perl->get_logger($cat) => ("Log::Log4perl", $cat)
  362.     #   (6)   L4pSubclass->get_logger($cat) => ("L4pSubclass", $cat)
  363.  
  364.     # Note that (4) L4pSubclass->get_logger() => ("L4pSubclass")
  365.     # is indistinguishable from (3) and therefore can't be allowed.
  366.     # Wrapper classes always have to specify the category explicitely.
  367.  
  368.     my $category;
  369.  
  370.     if(@_ == 0) {
  371.           # 1
  372.         my $level = 0;
  373.         do { $category = scalar caller($level++);
  374.         } while exists $WRAPPERS_REGISTERED{ $category };
  375.  
  376.     } elsif(@_ == 1) {
  377.           # 2, 3
  378.         $category = $_[0];
  379.  
  380.         my $level = 0;
  381.         while(exists $WRAPPERS_REGISTERED{ $category }) { 
  382.             $category = scalar caller($level++);
  383.         }
  384.  
  385.     } else {
  386.           # 5, 6
  387.         $category = $_[1];
  388.     }
  389.  
  390.     # Delegate this to the logger module
  391.     return Log::Log4perl::Logger->get_logger($category);
  392. }
  393.  
  394. ##################################################
  395. sub appenders {  # Get a hashref of all defined appender wrappers
  396. ##################################################
  397.     return \%Log::Log4perl::Logger::APPENDER_BY_NAME;
  398. }
  399.  
  400. ##################################################
  401. sub add_appender { # Add an appender to the system, but don't assign
  402.                # it to a logger yet
  403. ##################################################
  404.     my($class, $appender) = @_;
  405.  
  406.     my $name = $appender->name();
  407.     die "Mandatory parameter 'name' missing in appender" unless defined $name;
  408.  
  409.       # Make it known by name in the Log4perl universe
  410.       # (so that composite appenders can find it)
  411.     Log::Log4perl->appenders()->{ $name } = $appender;
  412. }
  413.  
  414. ##################################################
  415. # Return number of appenders changed
  416. sub appender_thresholds_adjust {  # Readjust appender thresholds
  417. ##################################################
  418.         # If someone calls L4p-> and not L4p::
  419.     shift if $_[0] eq __PACKAGE__;
  420.     my($delta, $appenders) = @_;
  421.     my $retval = 0;
  422.  
  423.     if($delta == 0) {
  424.           # Nothing to do, no delta given.
  425.         return;
  426.     }
  427.  
  428.     if(defined $appenders) {
  429.             # Map names to objects
  430.         $appenders = [map { 
  431.                        die "Unkown appender: '$_'" unless exists
  432.                           $Log::Log4perl::Logger::APPENDER_BY_NAME{
  433.                             $_};
  434.                        $Log::Log4perl::Logger::APPENDER_BY_NAME{
  435.                          $_} 
  436.                       } @$appenders];
  437.     } else {
  438.             # Just hand over all known appenders
  439.         $appenders = [values %{Log::Log4perl::appenders()}] unless 
  440.             defined $appenders;
  441.     }
  442.  
  443.         # Change all appender thresholds;
  444.     foreach my $app (@$appenders) {
  445.         my $old_thres = $app->threshold();
  446.         my $new_thres;
  447.         if($delta > 0) {
  448.             $new_thres = Log::Log4perl::Level::get_higher_level(
  449.                              $old_thres, $delta);
  450.         } else {
  451.             $new_thres = Log::Log4perl::Level::get_lower_level(
  452.                              $old_thres, -$delta);
  453.         }
  454.  
  455.         ++$retval if ($app->threshold($new_thres) == $new_thres);
  456.     }
  457.     return $retval;
  458. }
  459.  
  460. ##################################################
  461. sub appender_by_name {  # Get a (real) appender by name
  462. ##################################################
  463.         # If someone calls L4p->appender_by_name and not L4p::appender_by_name
  464.     shift if $_[0] eq __PACKAGE__;
  465.  
  466.     my($name) = @_;
  467.  
  468.     if(defined $name and
  469.        exists $Log::Log4perl::Logger::APPENDER_BY_NAME{
  470.                  $name}) {
  471.         return $Log::Log4perl::Logger::APPENDER_BY_NAME{
  472.                  $name}->{appender};
  473.     } else {
  474.         return undef;
  475.     }
  476. }
  477.  
  478. ##################################################
  479. sub eradicate_appender {  # Remove an appender from the system
  480. ##################################################
  481.         # If someone calls L4p->... and not L4p::...
  482.     shift if $_[0] eq __PACKAGE__;
  483.     Log::Log4perl::Logger->eradicate_appender(@_);
  484. }
  485.  
  486. ##################################################
  487. sub infiltrate_lwp {  # 
  488. ##################################################
  489.     no warnings qw(redefine);
  490.  
  491.     my $l4p_wrapper = sub {
  492.         my($prio, @message) = @_;
  493.         local $Log::Log4perl::caller_depth =
  494.               $Log::Log4perl::caller_depth + 2;
  495.         get_logger(scalar caller(1))->log($prio, @message);
  496.     };
  497.  
  498.     *LWP::Debug::trace = sub { 
  499.         $l4p_wrapper->($INFO, @_); 
  500.     };
  501.     *LWP::Debug::conns =
  502.     *LWP::Debug::debug = sub { 
  503.         $l4p_wrapper->($DEBUG, @_); 
  504.     };
  505. }
  506.  
  507. 1;
  508.  
  509. __END__
  510.  
  511. =head1 NAME
  512.  
  513. Log::Log4perl - Log4j implementation for Perl
  514.  
  515. =head1 SYNOPSIS
  516.  
  517.         # Easy mode if you like it simple ...
  518.  
  519.     use Log::Log4perl qw(:easy);
  520.     Log::Log4perl->easy_init($ERROR);
  521.  
  522.     DEBUG "This doesn't go anywhere";
  523.     ERROR "This gets logged";
  524.  
  525.         # ... or standard mode for more features:
  526.  
  527.     Log::Log4perl::init('/etc/log4perl.conf');
  528.     
  529.     --or--
  530.     
  531.         # Check config every 10 secs
  532.     Log::Log4perl::init_and_watch('/etc/log4perl.conf',10);
  533.  
  534.     --then--
  535.     
  536.     $logger = Log::Log4perl->get_logger('house.bedrm.desk.topdrwr');
  537.     
  538.     $logger->debug('this is a debug message');
  539.     $logger->info('this is an info message');
  540.     $logger->warn('etc');
  541.     $logger->error('..');
  542.     $logger->fatal('..');
  543.     
  544.     #####/etc/log4perl.conf###############################
  545.     log4perl.logger.house              = WARN,  FileAppndr1
  546.     log4perl.logger.house.bedroom.desk = DEBUG, FileAppndr1
  547.     
  548.     log4perl.appender.FileAppndr1      = Log::Log4perl::Appender::File
  549.     log4perl.appender.FileAppndr1.filename = desk.log 
  550.     log4perl.appender.FileAppndr1.layout   = \
  551.                             Log::Log4perl::Layout::SimpleLayout
  552.     ######################################################
  553.        
  554. =head1 ABSTRACT
  555.  
  556.     Log::Log4perl provides a powerful logging API for your application
  557.  
  558. =head1 DESCRIPTION
  559.  
  560. Log::Log4perl lets you remote-control and fine-tune the logging behaviour
  561. of your system from the outside. It implements the widely popular 
  562. (Java-based) Log4j logging package in pure Perl. 
  563.  
  564. B<For a detailed tutorial on Log::Log4perl usage, please read> 
  565.  
  566.     http://www.perl.com/pub/a/2002/09/11/log4perl.html
  567.  
  568. Logging beats a debugger if you want to know what's going on 
  569. in your code during runtime. However, traditional logging packages
  570. are too static and generate a flood of log messages in your log files
  571. that won't help you.
  572.  
  573. C<Log::Log4perl> is different. It allows you to control the number of 
  574. logging messages generated at three different levels:
  575.  
  576. =over 4
  577.  
  578. =item *
  579.  
  580. At a central location in your system (either in a configuration file or
  581. in the startup code) you specify I<which components> (classes, functions) 
  582. of your system should generate logs.
  583.  
  584. =item *
  585.  
  586. You specify how detailed the logging of these components should be by
  587. specifying logging I<levels>.
  588.  
  589. =item *
  590.  
  591. You also specify which so-called I<appenders> you want to feed your
  592. log messages to ("Print it to the screen and also append it to /tmp/my.log")
  593. and which format ("Write the date first, then the file name and line 
  594. number, and then the log message") they should be in.
  595.  
  596. =back
  597.  
  598. This is a very powerful and flexible mechanism. You can turn on and off
  599. your logs at any time, specify the level of detail and make that
  600. dependent on the subsystem that's currently executed. 
  601.  
  602. Let me give you an example: You might 
  603. find out that your system has a problem in the 
  604. C<MySystem::Helpers::ScanDir>
  605. component. Turning on detailed debugging logs all over the system would
  606. generate a flood of useless log messages and bog your system down beyond
  607. recognition. With C<Log::Log4perl>, however, you can tell the system:
  608. "Continue to log only severe errors to the log file. Open a second
  609. log file, turn on full debug logs in the C<MySystem::Helpers::ScanDir>
  610. component and dump all messages originating from there into the new
  611. log file". And all this is possible by just changing the parameters
  612. in a configuration file, which your system can re-read even 
  613. while it's running!
  614.  
  615. =head1 How to use it
  616.  
  617. The C<Log::Log4perl> package can be initialized in two ways: Either
  618. via Perl commands or via a C<log4j>-style configuration file.
  619.  
  620. =head2 Initialize via a configuration file
  621.  
  622. This is the easiest way to prepare your system for using
  623. C<Log::Log4perl>. Use a configuration file like this:
  624.  
  625.     ############################################################
  626.     # A simple root logger with a Log::Log4perl::Appender::File 
  627.     # file appender in Perl.
  628.     ############################################################
  629.     log4perl.rootLogger=ERROR, LOGFILE
  630.     
  631.     log4perl.appender.LOGFILE=Log::Log4perl::Appender::File
  632.     log4perl.appender.LOGFILE.filename=/var/log/myerrs.log
  633.     log4perl.appender.LOGFILE.mode=append
  634.     
  635.     log4perl.appender.LOGFILE.layout=PatternLayout
  636.     log4perl.appender.LOGFILE.layout.ConversionPattern=[%r] %F %L %c - %m%n
  637.  
  638. These lines define your standard logger that's appending severe
  639. errors to C</var/log/myerrs.log>, using the format
  640.  
  641.     [millisecs] source-filename line-number class - message newline
  642.  
  643. Assuming that this configuration file is saved as C<log.conf>, you need to 
  644. read it in in the startup section of your code, using the following
  645. commands:
  646.  
  647.   use Log::Log4perl;
  648.   Log::Log4perl->init("log.conf");
  649.  
  650. After that's done I<somewhere> in the code, you can retrieve
  651. logger objects I<anywhere> in the code. Note that
  652. there's no need to carry any logger references around with your 
  653. functions and methods. You can get a logger anytime via a singleton
  654. mechanism:
  655.  
  656.     package My::MegaPackage;
  657.     use  Log::Log4perl;
  658.  
  659.     sub some_method {
  660.         my($param) = @_;
  661.  
  662.         my $log = Log::Log4perl->get_logger("My::MegaPackage");
  663.  
  664.         $log->debug("Debug message");
  665.         $log->info("Info message");
  666.         $log->error("Error message");
  667.  
  668.         ...
  669.     }
  670.  
  671. With the configuration file above, C<Log::Log4perl> will write
  672. "Error message" to the specified log file, but won't do anything for 
  673. the C<debug()> and C<info()> calls, because the log level has been set
  674. to C<ERROR> for all components in the first line of 
  675. configuration file shown above.
  676.  
  677. Why C<Log::Log4perl-E<gt>get_logger> and
  678. not C<Log::Log4perl-E<gt>new>? We don't want to create a new
  679. object every time. Usually in OO-Programming, you create an object
  680. once and use the reference to it to call its methods. However,
  681. this requires that you pass around the object to all functions
  682. and the last thing we want is pollute each and every function/method
  683. we're using with a handle to the C<Logger>:
  684.  
  685.     sub function {  # Brrrr!!
  686.         my($logger, $some, $other, $parameters) = @_;
  687.     }
  688.  
  689. Instead, if a function/method wants a reference to the logger, it
  690. just calls the Logger's static C<get_logger($category)> method to obtain
  691. a reference to the I<one and only> possible logger object of
  692. a certain category.
  693. That's called a I<singleton> if you're a Gamma fan.
  694.  
  695. How does the logger know
  696. which messages it is supposed to log and which ones to suppress?
  697. C<Log::Log4perl> works with inheritance: The config file above didn't 
  698. specify anything about C<My::MegaPackage>. 
  699. And yet, we've defined a logger of the category 
  700. C<My::MegaPackage>.
  701. In this case, C<Log::Log4perl> will walk up the namespace hierarchy
  702. (C<My> and then we're at the root) to figure out if a log level is
  703. defined somewhere. In the case above, the log level at the root
  704. (root I<always> defines a log level, but not necessarily an appender)
  705. defines that 
  706. the log level is supposed to be C<ERROR> -- meaning that I<DEBUG>
  707. and I<INFO> messages are suppressed. Note that this 'inheritance' is
  708. unrelated to Perl's class inheritance, it is merely related to the
  709. logger namespace.
  710.  
  711. =head2 Log Levels
  712.  
  713. There are six predefined log levels: C<FATAL>, C<ERROR>, C<WARN>, C<INFO>,
  714. C<DEBUG>, and C<TRACE> (in descending priority). Your configured logging level
  715. has to at least match the priority of the logging message.
  716.  
  717. If your configured logging level is C<WARN>, then messages logged 
  718. with C<info()>, C<debug()>, and C<trace()> will be suppressed. 
  719. C<fatal()>, C<error()> and C<warn()> will make their way through,
  720. because their priority is higher or equal than the configured setting.
  721.  
  722. Instead of calling the methods
  723.  
  724.     $logger->trace("...");  # Log a trace message
  725.     $logger->debug("...");  # Log a debug message
  726.     $logger->info("...");   # Log a info message
  727.     $logger->warn("...");   # Log a warn message
  728.     $logger->error("...");  # Log a error message
  729.     $logger->fatal("...");  # Log a fatal message
  730.  
  731. you could also call the C<log()> method with the appropriate level
  732. using the constants defined in C<Log::Log4perl::Level>:
  733.  
  734.     use Log::Log4perl::Level;
  735.  
  736.     $logger->log($TRACE, "...");
  737.     $logger->log($DEBUG, "...");
  738.     $logger->log($INFO, "...");
  739.     $logger->log($WARN, "...");
  740.     $logger->log($ERROR, "...");
  741.     $logger->log($FATAL, "...");
  742.  
  743. But nobody does that, really. Neither does anyone need more logging
  744. levels than these predefined ones. If you think you do, I would
  745. suggest you look into steering your logging behaviour via
  746. the category mechanism.
  747.  
  748. If you need to find out if the currently configured logging
  749. level would allow a logger's logging statement to go through, use the
  750. logger's C<is_I<level>()> methods:
  751.  
  752.     $logger->is_trace()    # True if trace messages would go through
  753.     $logger->is_debug()    # True if debug messages would go through
  754.     $logger->is_info()     # True if info messages would go through
  755.     $logger->is_warn()     # True if warn messages would go through
  756.     $logger->is_error()    # True if error messages would go through
  757.     $logger->is_fatal()    # True if fatal messages would go through
  758.  
  759. Example: C<$logger-E<gt>is_warn()> returns true if the logger's current
  760. level, as derived from either the logger's category (or, in absence of
  761. that, one of the logger's parent's level setting) is 
  762. C<$WARN>, C<$ERROR> or C<$FATAL>.
  763.  
  764. Also available are a series of more Java-esque functions which return
  765. the same values. These are of the format C<isI<Level>Enabled()>,
  766. so C<$logger-E<gt>isDebugEnabled()> is synonymous to 
  767. C<$logger-E<gt>is_debug()>.
  768.  
  769.  
  770. These level checking functions
  771. will come in handy later, when we want to block unnecessary
  772. expensive parameter construction in case the logging level is too
  773. low to log the statement anyway, like in:
  774.  
  775.     if($logger->is_error()) {
  776.         $logger->error("Erroneous array: @super_long_array");
  777.     }
  778.  
  779. If we had just written
  780.  
  781.     $logger->error("Erroneous array: @super_long_array");
  782.  
  783. then Perl would have interpolated
  784. C<@super_long_array> into the string via an expensive operation
  785. only to figure out shortly after that the string can be ignored
  786. entirely because the configured logging level is lower than C<$ERROR>.
  787.  
  788. The to-be-logged
  789. message passed to all of the functions described above can
  790. consist of an arbitrary number of arguments, which the logging functions
  791. just chain together to a single string. Therefore
  792.  
  793.     $logger->debug("Hello ", "World", "!");  # and
  794.     $logger->debug("Hello World!");
  795.  
  796. are identical.
  797.  
  798. Note that even if one of the methods above returns true, it doesn't 
  799. necessarily mean that the message will actually get logged. 
  800. What is_debug() checks is that
  801. the logger used is configured to let a message of the given priority 
  802. (DEBUG) through. But after this check, Log4perl will eventually apply custom 
  803. filters and forward the message to one or more appenders. None of this
  804. gets checked by is_xxx(), for the simple reason that it's 
  805. impossible to know what a custom filter does with a message without
  806. having the actual message or what an appender does to a message without
  807. actually having it log it.
  808.  
  809. =head2 Log and die or warn
  810.  
  811. Often, when you croak / carp / warn / die, you want to log those messages.
  812. Rather than doing the following:
  813.  
  814.     $logger->fatal($err) && die($err);
  815.  
  816. you can use the following:
  817.  
  818.     $logger->logwarn();
  819.     $logger->logdie();
  820.  
  821. These print out log messages in the WARN and FATAL level, respectively,
  822. and then call the built-in warn() and die() functions. Since there is
  823. an ERROR level between WARN and FATAL, there are two additional helper
  824. functions in case you'd like to use ERROR for either warn() or die():
  825.  
  826.     $logger->error_warn();
  827.     $logger->error_die();
  828.  
  829. Finally, there's the Carp functions that do just what the Carp functions
  830. do, but with logging:
  831.  
  832.     $logger->logcarp();        # warn w/ 1-level stack trace
  833.     $logger->logcluck();       # warn w/ full stack trace
  834.     $logger->logcroak();       # die w/ 1-level stack trace
  835.     $logger->logconfess();     # die w/ full stack trace
  836.  
  837. =head2 Appenders
  838.  
  839. If you don't define any appenders, nothing will happen. Appenders will
  840. be triggered whenever the configured logging level requires a message
  841. to be logged and not suppressed.
  842.  
  843. C<Log::Log4perl> doesn't define any appenders by default, not even the root
  844. logger has one.
  845.  
  846. C<Log::Log4perl> already comes with a standard set of appenders:
  847.  
  848.     Log::Log4perl::Appender::Screen
  849.     Log::Log4perl::Appender::ScreenColoredLevels
  850.     Log::Log4perl::Appender::File
  851.     Log::Log4perl::Appender::Socket
  852.     Log::Log4perl::Appender::DBI
  853.     Log::Log4perl::Appender::Synchronized
  854.     Log::Log4perl::Appender::RRDs
  855.  
  856. to log to the screen, to files and to databases. 
  857.  
  858. On CPAN, you can find additional appenders like
  859.  
  860.     Log::Log4perl::Layout::XMLLayout
  861.  
  862. by Guido Carls E<lt>gcarls@cpan.orgE<gt>.
  863. It allows for hooking up Log::Log4perl with the graphical Log Analyzer
  864. Chainsaw (see 
  865. L<Log::Log4perl::FAQ/"Can I use Log::Log4perl with log4j's Chainsaw?">).
  866.  
  867. =head2 Additional Appenders via Log::Dispatch
  868.  
  869. C<Log::Log4perl> also supports I<Dave Rolskys> excellent C<Log::Dispatch>
  870. framework which implements a wide variety of different appenders. 
  871.  
  872. Here's the list of appender modules currently available via C<Log::Dispatch>:
  873.  
  874.        Log::Dispatch::ApacheLog
  875.        Log::Dispatch::DBI (by Tatsuhiko Miyagawa)
  876.        Log::Dispatch::Email,
  877.        Log::Dispatch::Email::MailSend,
  878.        Log::Dispatch::Email::MailSendmail,
  879.        Log::Dispatch::Email::MIMELite
  880.        Log::Dispatch::File
  881.        Log::Dispatch::FileRotate (by Mark Pfeiffer)
  882.        Log::Dispatch::Handle
  883.        Log::Dispatch::Screen
  884.        Log::Dispatch::Syslog
  885.        Log::Dispatch::Tk (by Dominique Dumont)
  886.  
  887. Please note that in order to use any of these additional appenders, you
  888. have to fetch Log::Dispatch from CPAN and install it. Also the particular
  889. appender you're using might require installing the particular module.
  890.  
  891. For additional information on appenders, please check the
  892. L<Log::Log4perl::Appender> manual page.
  893.  
  894. =head2 Appender Example
  895.  
  896. Now let's assume that we want to log C<info()> or
  897. higher prioritized messages in the C<Foo::Bar> category
  898. to both STDOUT and to a log file, say C<test.log>.
  899. In the initialization section of your system,
  900. just define two appenders using the readily available
  901. C<Log::Log4perl::Appender::File> and C<Log::Log4perl::Appender::Screen> 
  902. modules:
  903.  
  904.   use Log::Log4perl;
  905.  
  906.      # Configuration in a string ...
  907.   my $conf = q(
  908.     log4perl.category.Foo.Bar          = INFO, Logfile, Screen
  909.  
  910.     log4perl.appender.Logfile          = Log::Log4perl::Appender::File
  911.     log4perl.appender.Logfile.filename = test.log
  912.     log4perl.appender.Logfile.layout   = Log::Log4perl::Layout::PatternLayout
  913.     log4perl.appender.Logfile.layout.ConversionPattern = [%r] %F %L %m%n
  914.  
  915.     log4perl.appender.Screen         = Log::Log4perl::Appender::Screen
  916.     log4perl.appender.Screen.stderr  = 0
  917.     log4perl.appender.Screen.layout = Log::Log4perl::Layout::SimpleLayout
  918.   );
  919.  
  920.      # ... passed as a reference to init()
  921.   Log::Log4perl::init( \$conf );
  922.  
  923. Once the initialization shown above has happened once, typically in
  924. the startup code of your system, just use the defined logger anywhere in 
  925. your system:
  926.  
  927.   ##########################
  928.   # ... in some function ...
  929.   ##########################
  930.   my $log = Log::Log4perl::get_logger("Foo::Bar");
  931.  
  932.     # Logs both to STDOUT and to the file test.log
  933.   $log->info("Important Info!");
  934.  
  935. The C<layout> settings specified in the configuration section define the 
  936. format in which the
  937. message is going to be logged by the specified appender. The format shown
  938. for the file appender is logging not only the message but also the number of
  939. milliseconds since the program has started (%r), the name of the file
  940. the call to the logger has happened and the line number there (%F and
  941. %L), the message itself (%m) and a OS-specific newline character (%n):
  942.  
  943.     [187] ./myscript.pl 27 Important Info!
  944.  
  945. The
  946. screen appender above, on the other hand, 
  947. uses a C<SimpleLayout>, which logs the 
  948. debug level, a hyphen (-) and the log message:
  949.  
  950.     INFO - Important Info!
  951.  
  952. For more detailed info on layout formats, see L<Log Layouts>. 
  953.  
  954. In the configuration sample above, we chose to define a I<category> 
  955. logger (C<Foo::Bar>).
  956. This will cause only messages originating from
  957. this specific category logger to be logged in the defined format
  958. and locations.
  959.  
  960. =head2 Logging newlines
  961.  
  962. There's some controversy between different logging systems as to when and 
  963. where newlines are supposed to be added to logged messages.
  964.  
  965. The Log4perl way is that a logging statement I<should not> 
  966. contain a newline:
  967.  
  968.     $logger->info("Some message");
  969.     $logger->info("Another message");
  970.  
  971. If this is supposed to end up in a log file like
  972.  
  973.     Some message
  974.     Another message
  975.  
  976. then an appropriate appender layout like "%m%n" will take care of adding
  977. a newline at the end of each message to make sure every message is 
  978. printed on its own line.
  979.  
  980. Other logging systems, Log::Dispatch in particular, recommend adding the
  981. newline to the log statement. This doesn't work well, however, if you, say,
  982. replace your file appender by a database appender, and all of a sudden
  983. those newlines scattered around the code don't make sense anymore.
  984.  
  985. Assigning matching layouts to different appenders and leaving newlines
  986. out of the code solves this problem. If you inherited code that has logging
  987. statements with newlines and want to make it work with Log4perl, read
  988. the L<Log::Log4perl::Layout::PatternLayout> documentation on how to 
  989. accomplish that.
  990.  
  991. =head2 Configuration files
  992.  
  993. As shown above, you can define C<Log::Log4perl> loggers both from within
  994. your Perl code or from configuration files. The latter have the unbeatable
  995. advantage that you can modify your system's logging behaviour without 
  996. interfering with the code at all. So even if your code is being run by 
  997. somebody who's totally oblivious to Perl, they still can adapt the
  998. module's logging behaviour to their needs.
  999.  
  1000. C<Log::Log4perl> has been designed to understand C<Log4j> configuration
  1001. files -- as used by the original Java implementation. Instead of 
  1002. reiterating the format description in [2], let me just list three
  1003. examples (also derived from [2]), which should also illustrate
  1004. how it works:
  1005.  
  1006.     log4j.rootLogger=DEBUG, A1
  1007.     log4j.appender.A1=org.apache.log4j.ConsoleAppender
  1008.     log4j.appender.A1.layout=org.apache.log4j.PatternLayout
  1009.     log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c %x - %m%n
  1010.  
  1011. This enables messages of priority C<DEBUG> or higher in the root
  1012. hierarchy and has the system write them to the console. 
  1013. C<ConsoleAppender> is a Java appender, but C<Log::Log4perl> jumps
  1014. through a significant number of hoops internally to map these to their
  1015. corresponding Perl classes, C<Log::Log4perl::Appender::Screen> in this case.
  1016.  
  1017. Second example:
  1018.  
  1019.     log4perl.rootLogger=DEBUG, A1
  1020.     log4perl.appender.A1=Log::Log4perl::Appender::Screen
  1021.     log4perl.appender.A1.layout=PatternLayout
  1022.     log4perl.appender.A1.layout.ConversionPattern=%d %-5p %c - %m%n
  1023.     log4perl.logger.com.foo=WARN
  1024.  
  1025. This defines two loggers: The root logger and the C<com.foo> logger.
  1026. The root logger is easily triggered by debug-messages, 
  1027. but the C<com.foo> logger makes sure that messages issued within
  1028. the C<Com::Foo> component and below are only forwarded to the appender
  1029. if they're of priority I<warning> or higher. 
  1030.  
  1031. Note that the C<com.foo> logger doesn't define an appender. Therefore,
  1032. it will just propagate the message up the hierarchy until the root logger
  1033. picks it up and forwards it to the one and only appender of the root
  1034. category, using the format defined for it.
  1035.  
  1036. Third example:
  1037.  
  1038.     log4j.rootLogger=debug, stdout, R
  1039.     log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  1040.     log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  1041.     log4j.appender.stdout.layout.ConversionPattern=%5p (%F:%L) - %m%n
  1042.     log4j.appender.R=org.apache.log4j.RollingFileAppender
  1043.     log4j.appender.R.File=example.log
  1044.     log4j.appender.R.layout=org.apache.log4j.PatternLayout
  1045.     log4j.appender.R.layout.ConversionPattern=%p %c - %m%n
  1046.  
  1047. The root logger defines two appenders here: C<stdout>, which uses 
  1048. C<org.apache.log4j.ConsoleAppender> (ultimately mapped by C<Log::Log4perl>
  1049. to C<Log::Log4perl::Appender::Screen>) to write to the screen. And
  1050. C<R>, a C<org.apache.log4j.RollingFileAppender> 
  1051. (mapped by C<Log::Log4perl> to 
  1052. C<Log::Dispatch::FileRotate> with the C<File> attribute specifying the
  1053. log file.
  1054.  
  1055. See L<Log::Log4perl::Config> for more examples and syntax explanations.
  1056.  
  1057. =head2 Log Layouts
  1058.  
  1059. If the logging engine passes a message to an appender, because it thinks
  1060. it should be logged, the appender doesn't just
  1061. write it out haphazardly. There's ways to tell the appender how to format
  1062. the message and add all sorts of interesting data to it: The date and
  1063. time when the event happened, the file, the line number, the
  1064. debug level of the logger and others.
  1065.  
  1066. There's currently two layouts defined in C<Log::Log4perl>: 
  1067. C<Log::Log4perl::Layout::SimpleLayout> and
  1068. C<Log::Log4perl::Layout::PatternLayout>:
  1069.  
  1070. =over 4 
  1071.  
  1072. =item C<Log::Log4perl::SimpleLayout> 
  1073.  
  1074. formats a message in a simple
  1075. way and just prepends it by the debug level and a hyphen:
  1076. C<"$level - $message>, for example C<"FATAL - Can't open password file">.
  1077.  
  1078. =item C<Log::Log4perl::Layout::PatternLayout> 
  1079.  
  1080. on the other hand is very powerful and 
  1081. allows for a very flexible format in C<printf>-style. The format
  1082. string can contain a number of placeholders which will be
  1083. replaced by the logging engine when it's time to log the message:
  1084.  
  1085.     %c Category of the logging event.
  1086.     %C Fully qualified package (or class) name of the caller
  1087.     %d Current date in yyyy/MM/dd hh:mm:ss format
  1088.     %F File where the logging event occurred
  1089.     %H Hostname (if Sys::Hostname is available)
  1090.     %l Fully qualified name of the calling method followed by the
  1091.        callers source the file name and line number between 
  1092.        parentheses.
  1093.     %L Line number within the file where the log statement was issued
  1094.     %m The message to be logged
  1095.     %m{chomp} The message to be logged, stripped off a trailing newline
  1096.     %M Method or function where the logging request was issued
  1097.     %n Newline (OS-independent)
  1098.     %p Priority of the logging event
  1099.     %P pid of the current process
  1100.     %r Number of milliseconds elapsed from program start to logging 
  1101.        event
  1102.     %R Number of milliseconds elapsed from last logging event to
  1103.        current logging event 
  1104.     %T A stack trace of functions called
  1105.     %x The topmost NDC (see below)
  1106.     %X{key} The entry 'key' of the MDC (see below)
  1107.     %% A literal percent (%) sign
  1108.  
  1109. NDC and MDC are explained in L<"Nested Diagnostic Context (NDC)">
  1110. and L<"Mapped Diagnostic Context (MDC)">.
  1111.  
  1112. Also, C<%d> can be fine-tuned to display only certain characteristics
  1113. of a date, according to the SimpleDateFormat in the Java World
  1114. (http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html)
  1115.  
  1116. In this way, C<%d{HH:mm}> displays only hours and minutes of the current date,
  1117. while C<%d{yy, EEEE}> displays a two-digit year, followed by a spelled-out
  1118. (like C<Wednesday>). 
  1119.  
  1120. Similar options are available for shrinking the displayed category or
  1121. limit file/path components, C<%F{1}> only displays the source file I<name>
  1122. without any path components while C<%F> logs the full path. %c{2} only
  1123. logs the last two components of the current category, C<Foo::Bar::Baz> 
  1124. becomes C<Bar::Baz> and saves space.
  1125.  
  1126. If those placeholders aren't enough, then you can define your own right in
  1127. the config file like this:
  1128.  
  1129.     log4perl.PatternLayout.cspec.U = sub { return "UID $<" }
  1130.  
  1131. See L<Log::Log4perl::Layout::PatternLayout> for further details on
  1132. customized specifiers.
  1133.  
  1134. Please note that the subroutines you're defining in this way are going
  1135. to be run in the C<main> namespace, so be sure to fully qualify functions
  1136. and variables if they're located in different packages.
  1137.     
  1138. SECURITY NOTE: this feature means arbitrary perl code can be embedded in the 
  1139. config file.  In the rare case where the people who have access to your config 
  1140. file are different from the people who write your code and shouldn't have 
  1141. execute rights, you might want to call
  1142.  
  1143.     Log::Log4perl::Config->allow_code(0);
  1144.  
  1145. before you call init(). Alternatively you can supply a restricted set of
  1146. Perl opcodes that can be embedded in the config file as described in
  1147. L<"Restricting what Opcodes can be in a Perl Hook">.
  1148.  
  1149. =back
  1150.  
  1151. All placeholders are quantifiable, just like in I<printf>. Following this 
  1152. tradition, C<%-20c> will reserve 20 chars for the category and left-justify it.
  1153.  
  1154. For more details on logging and how to use the flexible and the simple
  1155. format, check out the original C<log4j> website under
  1156.  
  1157.     http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/SimpleLayout.html
  1158.     http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html
  1159.  
  1160. =head2 Penalties
  1161.  
  1162. Logging comes with a price tag. C<Log::Log4perl> has been optimized
  1163. to allow for maximum performance, both with logging enabled and disabled.
  1164.  
  1165. But you need to be aware that there's a small hit every time your code
  1166. encounters a log statement -- no matter if logging is enabled or not. 
  1167. C<Log::Log4perl> has been designed to keep this so low that it will
  1168. be unnoticable to most applications.
  1169.  
  1170. Here's a couple of tricks which help C<Log::Log4perl> to avoid
  1171. unnecessary delays:
  1172.  
  1173. You can save serious time if you're logging something like
  1174.  
  1175.         # Expensive in non-debug mode!
  1176.     for (@super_long_array) {
  1177.         $logger->debug("Element: $_");
  1178.     }
  1179.  
  1180. and C<@super_long_array> is fairly big, so looping through it is pretty
  1181. expensive. Only you, the programmer, knows that going through that C<for>
  1182. loop can be skipped entirely if the current logging level for the 
  1183. actual component is higher than C<debug>.
  1184. In this case, use this instead:
  1185.  
  1186.         # Cheap in non-debug mode!
  1187.     if($logger->is_debug()) {
  1188.         for (@super_long_array) {
  1189.             $logger->debug("Element: $_");
  1190.         }
  1191.     }
  1192.  
  1193. If you're afraid that generating the parameters to the
  1194. logging function is fairly expensive, use closures:
  1195.  
  1196.         # Passed as subroutine ref
  1197.     use Data::Dumper;
  1198.     $logger->debug(sub { Dumper($data) } );
  1199.  
  1200. This won't unravel C<$data> via Dumper() unless it's actually needed
  1201. because it's logged. 
  1202.  
  1203. Also, Log::Log4perl lets you specify arguments
  1204. to logger functions in I<message output filter syntax>:
  1205.  
  1206.     $logger->debug("Structure: ",
  1207.                    { filter => \&Dumper,
  1208.                      value  => $someref });
  1209.  
  1210. In this way, shortly before Log::Log4perl sending the
  1211. message out to any appenders, it will be searching all arguments for
  1212. hash references and treat them in a special way:
  1213.  
  1214. It will invoke the function given as a reference with the C<filter> key
  1215. (C<Data::Dumper::Dumper()>) and pass it the value that came with
  1216. the key named C<value> as an argument.
  1217. The anonymous hash in the call above will be replaced by the return 
  1218. value of the filter function.
  1219.  
  1220. =head1 Categories
  1221.  
  1222. B<Categories are also called "Loggers" in Log4perl, both refer
  1223. to the the same thing and these terms are used interchangeably.>
  1224. C<Log::Log4perl> uses I<categories> to determine if a log statement in
  1225. a component should be executed or suppressed at the current logging level.
  1226. Most of the time, these categories are just the classes the log statements
  1227. are located in:
  1228.  
  1229.     package Candy::Twix;
  1230.  
  1231.     sub new { 
  1232.         my $logger = Log::Log4perl->new("Candy::Twix");
  1233.         $logger->debug("Creating a new Twix bar");
  1234.         bless {}, shift;
  1235.     }
  1236.  
  1237.     # ...
  1238.  
  1239.     package Candy::Snickers;
  1240.  
  1241.     sub new { 
  1242.         my $logger = Log::Log4perl->new("Candy.Snickers");
  1243.         $logger->debug("Creating a new Snickers bar");
  1244.         bless {}, shift;
  1245.     }
  1246.  
  1247.     # ...
  1248.  
  1249.     package main;
  1250.     Log::Log4perl->init("mylogdefs.conf");
  1251.  
  1252.         # => "LOG> Creating a new Snickers bar"
  1253.     my $first = Candy::Snickers->new();
  1254.         # => "LOG> Creating a new Twix bar"
  1255.     my $second = Candy::Twix->new();
  1256.  
  1257. Note that you can separate your category hierarchy levels
  1258. using either dots like
  1259. in Java (.) or double-colons (::) like in Perl. Both notations
  1260. are equivalent and are handled the same way internally.
  1261.  
  1262. However, categories are just there to make
  1263. use of inheritance: if you invoke a logger in a sub-category, 
  1264. it will bubble up the hierarchy and call the appropriate appenders.
  1265. Internally, categories are not related to the class hierarchy of the program
  1266. at all -- they're purely virtual. You can use arbitrary categories --
  1267. for example in the following program, which isn't oo-style, but
  1268. procedural:
  1269.  
  1270.     sub print_portfolio {
  1271.  
  1272.         my $log = Log::Log4perl->new("user.portfolio");
  1273.         $log->debug("Quotes requested: @_");
  1274.  
  1275.         for(@_) {
  1276.             print "$_: ", get_quote($_), "\n";
  1277.         }
  1278.     }
  1279.  
  1280.     sub get_quote {
  1281.  
  1282.         my $log = Log::Log4perl->new("internet.quotesystem");
  1283.         $log->debug("Fetching quote: $_[0]");
  1284.  
  1285.         return yahoo_quote($_[0]);
  1286.     }
  1287.  
  1288. The logger in first function, C<print_portfolio>, is assigned the
  1289. (virtual) C<user.portfolio> category. Depending on the C<Log4perl>
  1290. configuration, this will either call a C<user.portfolio> appender,
  1291. a C<user> appender, or an appender assigned to root -- without
  1292. C<user.portfolio> having any relevance to the class system used in 
  1293. the program.
  1294. The logger in the second function adheres to the 
  1295. C<internet.quotesystem> category -- again, maybe because it's bundled 
  1296. with other Internet functions, but not because there would be
  1297. a class of this name somewhere.
  1298.  
  1299. However, be careful, don't go overboard: if you're developing a system
  1300. in object-oriented style, using the class hierarchy is usually your best
  1301. choice. Think about the people taking over your code one day: The
  1302. class hierarchy is probably what they know right up front, so it's easy
  1303. for them to tune the logging to their needs.
  1304.  
  1305. =head2 Turn off a component
  1306.  
  1307. C<Log4perl> doesn't only allow you to selectively switch I<on> a category
  1308. of log messages, you can also use the mechanism to selectively I<disable>
  1309. logging in certain components whereas logging is kept turned on in higher-level
  1310. categories. This mechanism comes in handy if you find that while bumping 
  1311. up the logging level of a high-level (i. e. close to root) category, 
  1312. that one component logs more than it should, 
  1313.  
  1314. Here's how it works: 
  1315.  
  1316.     ############################################################
  1317.     # Turn off logging in a lower-level category while keeping
  1318.     # it active in higher-level categories.
  1319.     ############################################################
  1320.     log4perl.rootLogger=DEBUG, LOGFILE
  1321.     log4perl.logger.deep.down.the.hierarchy = ERROR, LOGFILE
  1322.  
  1323.     # ... Define appenders ...
  1324.  
  1325. This way, log messages issued from within 
  1326. C<Deep::Down::The::Hierarchy> and below will be
  1327. logged only if they're C<ERROR> or worse, while in all other system components
  1328. even C<DEBUG> messages will be logged.
  1329.  
  1330. =head2 Return Values
  1331.  
  1332. All logging methods return values indicating if their message
  1333. actually reached one or more appenders. If the message has been
  1334. suppressed because of level constraints, C<undef> is returned.
  1335.  
  1336. For example,
  1337.  
  1338.     my $ret = $logger->info("Message");
  1339.  
  1340. will return C<undef> if the system debug level for the current category
  1341. is not C<INFO> or more permissive. 
  1342. If Log::Log4perl
  1343. forwarded the message to one or more appenders, the number of appenders
  1344. is returned.
  1345.  
  1346. If appenders decide to veto on the message with an appender threshold,
  1347. the log method's return value will have them excluded. This means that if
  1348. you've got one appender holding an appender threshold and you're 
  1349. logging a message
  1350. which passes the system's log level hurdle but not the appender threshold,
  1351. C<0> will be returned by the log function.
  1352.  
  1353. The bottom line is: Logging functions will return a I<true> value if the message
  1354. made it through to one or more appenders and a I<false> value if it didn't.
  1355. This allows for constructs like
  1356.  
  1357.     $logger->fatal("@_") or print STDERR "@_\n";
  1358.  
  1359. which will ensure that the fatal message isn't lost
  1360. if the current level is lower than FATAL or printed twice if 
  1361. the level is acceptable but an appender already points to STDERR.
  1362.  
  1363. =head2 Pitfalls with Categories
  1364.  
  1365. Be careful with just blindly reusing the system's packages as
  1366. categories. If you do, you'll get into trouble with inherited methods.
  1367. Imagine the following class setup:
  1368.  
  1369.     use Log::Log4perl;
  1370.  
  1371.     ###########################################
  1372.     package Bar;
  1373.     ###########################################
  1374.     sub new {
  1375.         my($class) = @_;
  1376.         my $logger = Log::Log4perl::get_logger(__PACKAGE__);
  1377.         $logger->debug("Creating instance");
  1378.         bless {}, $class;
  1379.     }
  1380.     ###########################################
  1381.     package Bar::Twix;
  1382.     ###########################################
  1383.     our @ISA = qw(Bar);
  1384.  
  1385.     ###########################################
  1386.     package main;
  1387.     ###########################################
  1388.     Log::Log4perl->init(\ qq{
  1389.     log4perl.category.Bar.Twix = DEBUG, Screen
  1390.     log4perl.appender.Screen = Log::Log4perl::Appender::Screen
  1391.     log4perl.appender.Screen.layout = SimpleLayout
  1392.     });
  1393.  
  1394.     my $bar = Bar::Twix->new();
  1395.  
  1396. C<Bar::Twix> just inherits everything from C<Bar>, including the constructor
  1397. C<new()>.
  1398. Contrary to what you might be thinking at first, this won't log anything. 
  1399. Reason for this is the C<get_logger()> call in package C<Bar>, which
  1400. will always get a logger of the C<Bar> category, even if we call C<new()> via
  1401. the C<Bar::Twix> package, which will make perl go up the inheritance 
  1402. tree to actually execute C<Bar::new()>. Since we've only defined logging
  1403. behaviour for C<Bar::Twix> in the configuration file, nothing will happen.
  1404.  
  1405. This can be fixed by changing the C<get_logger()> method in C<Bar::new()>
  1406. to obtain a logger of the category matching the
  1407. I<actual> class of the object, like in
  1408.  
  1409.         # ... in Bar::new() ...
  1410.     my $logger = Log::Log4perl::get_logger($class);
  1411.  
  1412. This way, you'll make sure the logger logs appropriately, 
  1413. no matter if the method is inherited or called directly.
  1414. C<new()> always gets the
  1415. real class name as an argument and all other methods can determine it 
  1416. via C<ref($self)>), so it shouldn't be a problem to get the right class
  1417. every time.
  1418.  
  1419. =head2 Initialize once and only once
  1420.  
  1421. It's important to realize that Log::Log4perl gets initialized once and only
  1422. once, typically at the start of a program or system. Calling C<init()>
  1423. more than once will cause it to clobber the existing configuration and
  1424. I<replace> it by the new one.
  1425.  
  1426. If you're in a traditional CGI environment, where every request is
  1427. handeled by a new process, calling C<init()> every time is fine. In
  1428. persistent environments like C<mod_perl>, however, Log::Log4perl
  1429. should be initialized either at system startup time (Apache offers
  1430. startup handlers for that) or via
  1431.  
  1432.         # Init or skip if already done
  1433.     Log::Log4perl->init_once($conf_file);
  1434.  
  1435. C<init_once()> is identical to C<init()>, just with the exception
  1436. that it will leave a potentially existing configuration alone and 
  1437. will only call C<init()> if Log::Log4perl hasn't been initialized yet.
  1438.  
  1439. If you're just curious if Log::Log4perl has been initialized yet, the
  1440. check
  1441.  
  1442.     if(Log::Log4perl->initialized()) {
  1443.         # Yes, Log::Log4perl has already been initialized
  1444.     } else {
  1445.         # No, not initialized yet ...
  1446.     }
  1447.  
  1448. can be used.
  1449.  
  1450. If you're afraid that the components of your system are stepping on 
  1451. each other's toes or if you are thinking that different components should
  1452. initialize Log::Log4perl seperately, try to consolidate your system
  1453. to use a centralized Log4perl configuration file and use 
  1454. Log4perl's I<categories> to separate your components.
  1455.  
  1456. =head2 Custom Filters
  1457.  
  1458. Log4perl allows the use of customized filters in its appenders
  1459. to control the output of messages. These filters might grep for
  1460. certain text chunks in a message, verify that its priority
  1461. matches or exceeds a certain level or that this is the 10th
  1462. time the same message has been submitted -- and come to a log/no log 
  1463. decision based upon these circumstantial facts.
  1464.  
  1465. Check out L<Log::Log4perl::Filter> for detailed instructions 
  1466. on how to use them.
  1467.  
  1468. =head2 Performance
  1469.  
  1470. The performance of Log::Log4perl calls obviously depends on a lot of things.
  1471. But to give you a general idea, here's some rough numbers:
  1472.  
  1473. On a Pentium 4 Linux box at 2.4 GHz, you'll get through
  1474.  
  1475. =over 4
  1476.  
  1477. =item *
  1478.  
  1479. 500,000 suppressed log statements per second
  1480.  
  1481. =item *
  1482.  
  1483. 30,000 logged messages per second (using an in-memory appender)
  1484.  
  1485. =item *
  1486.  
  1487. init_and_watch delay mode: 300,000 suppressed, 30,000 logged.
  1488. init_and_watch signal mode: 450,000 suppressed, 30,000 logged.
  1489.  
  1490. =back
  1491.  
  1492. Numbers depend on the complexity of the Log::Log4perl configuration.
  1493. For a more detailed benchmark test, check the C<docs/benchmark.results.txt> 
  1494. document in the Log::Log4perl distribution.
  1495.  
  1496. =head1 Cool Tricks
  1497.  
  1498. Here's a collection of useful tricks for the advanced C<Log::Log4perl> user.
  1499. For more, check the the FAQ, either in the distribution 
  1500. (L<Log::Log4perl::FAQ>) or on http://log4perl.sourceforge.net.
  1501.  
  1502. =head2 Shortcuts
  1503.  
  1504. When getting an instance of a logger, instead of saying
  1505.  
  1506.     use Log::Log4perl;
  1507.     my $logger = Log::Log4perl->get_logger();
  1508.  
  1509. it's often more convenient to import the C<get_logger> method from 
  1510. C<Log::Log4perl> into the current namespace:
  1511.  
  1512.     use Log::Log4perl qw(get_logger);
  1513.     my $logger = get_logger();
  1514.  
  1515. Please note this difference: To obtain the root logger, please use
  1516. C<get_logger("")>, call it without parameters (C<get_logger()>), you'll
  1517. get the logger of a category named after the current package. 
  1518. C<get_logger()> is equivalent to C<get_logger(__PACKAGE__)>.
  1519.  
  1520. =head2 Alternative initialization
  1521.  
  1522. Instead of having C<init()> read in a configuration file by specifying
  1523. a file name or passing it a reference to an open filehandle
  1524. (C<Log::Log4perl-E<gt>init( \*FILE )>),
  1525. you can 
  1526. also pass in a reference to a string, containing the content of
  1527. the file:
  1528.  
  1529.     Log::Log4perl->init( \$config_text );
  1530.  
  1531. Also, if you've got the C<name=value> pairs of the configuration in
  1532. a hash, you can just as well initialize C<Log::Log4perl> with
  1533. a reference to it:
  1534.  
  1535.     my %key_value_pairs = (
  1536.         "log4perl.rootLogger"       => "ERROR, LOGFILE",
  1537.         "log4perl.appender.LOGFILE" => "Log::Log4perl::Appender::File",
  1538.         ...
  1539.     );
  1540.  
  1541.     Log::Log4perl->init( \%key_value_pairs );
  1542.  
  1543. Or also you can use a URL, see below:
  1544.  
  1545. =head2 Using LWP to parse URLs
  1546.  
  1547. (This section borrowed from XML::DOM::Parser by T.J. Mather).
  1548.  
  1549. The init() function now also supports URLs, e.g. I<http://www.erols.com/enno/xsa.xml>.
  1550. It uses LWP to download the file and then calls parse() on the resulting string.
  1551. By default it will use a L<LWP::UserAgent> that is created as follows:
  1552.  
  1553.  use LWP::UserAgent;
  1554.  $LWP_USER_AGENT = LWP::UserAgent->new;
  1555.  $LWP_USER_AGENT->env_proxy;
  1556.  
  1557. Note that env_proxy reads proxy settings from environment variables, which is what I need to
  1558. do to get thru our firewall. If you want to use a different LWP::UserAgent, you can 
  1559. set it with
  1560.  
  1561.     Log::Log4perl::Config::set_LWP_UserAgent($my_agent);
  1562.  
  1563. Currently, LWP is used when the filename (passed to parsefile) starts with one of
  1564. the following URL schemes: http, https, ftp, wais, gopher, or file (followed by a colon.)
  1565.  
  1566. Don't use this feature with init_and_watch().
  1567.  
  1568. =head2 Automatic reloading of changed configuration files
  1569.  
  1570. Instead of just statically initializing Log::Log4perl via
  1571.  
  1572.     Log::Log4perl->init($conf_file);
  1573.  
  1574. there's a way to have Log::Log4perl periodically check for changes
  1575. in the configuration and reload it if necessary:
  1576.  
  1577.     Log::Log4perl->init_and_watch($conf_file, $delay);
  1578.  
  1579. In this mode, Log::Log4perl will examine the configuration file 
  1580. C<$conf_file> every C<$delay> seconds for changes via the file's
  1581. last modification timestamp. If the file has been updated, it will
  1582. be reloaded and replace the current Log::Log4perl configuration.
  1583.  
  1584. The way this works is that with every logger function called 
  1585. (debug(), is_debug(), etc.), Log::Log4perl will check if the delay 
  1586. interval has expired. If so, it will run a -M file check on the 
  1587. configuration file. If its timestamp has been modified, the current
  1588. configuration will be dumped and new content of the file will be
  1589. loaded.
  1590.  
  1591. This convenience comes at a price, though: Calling time() with every
  1592. logging function call, especially the ones that are "suppressed" (!), 
  1593. will slow down these Log4perl calls by about 40%.
  1594.  
  1595. To alleviate this performance hit a bit, C<init_and_watch()> 
  1596. can be configured to listen for a Unix signal to reload the 
  1597. configuration instead:
  1598.  
  1599.     Log::Log4perl->init_and_watch($conf_file, 'HUP');
  1600.  
  1601. This will set up a signal handler for SIGHUP and reload the configuration
  1602. if the application receives this signal, e.g. via the C<kill> command:
  1603.  
  1604.     kill -HUP pid
  1605.  
  1606. where C<pid> is the process ID of the application. This will bring you back
  1607. to about 85% of Log::Log4perl's normal execution speed for suppressed
  1608. statements. For details, check out L<"Performance">. For more info
  1609. on the signal handler, look for L<Log::Log4perl::Config::Watch/"SIGNAL MODE">.
  1610.  
  1611. If you have a somewhat long delay set between physical config file checks
  1612. or don't want to use the signal associated with the config file watcher,
  1613. you can trigger a configuration reload at the next possible time by
  1614. calling C<Log::Log4perl::Config-E<gt>watcher-E<gt>force_next_check()>.
  1615.  
  1616. One thing to watch out for: If the configuration file contains a syntax
  1617. or other fatal error, a running application will stop with C<die> if
  1618. this damaged configuration will be loaded during runtime, triggered
  1619. either by a signal or if the delay period expired and the change is 
  1620. detected. This behaviour might change in the future.
  1621.  
  1622. To allow the application to intercept and control a configuration reload
  1623. in init_and_watch mode, a callback can be specified:
  1624.  
  1625.     Log::Log4perl->init_and_watch($conf_file, 10, { 
  1626.             preinit_callback => \&callback });
  1627.  
  1628. If Log4perl determines that the configuration needs to be reloaded, it will
  1629. call the C<preinit_callback> function without parameters. If the callback
  1630. returns a true value, Log4perl will proceed and reload the configuration.  If
  1631. the callback returns a false value, Log4perl will keep the old configuration
  1632. and skip reloading it until the next time around.  Inside the callback, an
  1633. application can run all kinds of checks, including accessing the configuration
  1634. file, which is available via
  1635. C<Log::Log4perl::Config-E<gt>watcher()-E<gt>file()>.
  1636.  
  1637. =head2 Variable Substitution
  1638.  
  1639. To avoid having to retype the same expressions over and over again,
  1640. Log::Log4perl's configuration files support simple variable substitution.
  1641. New variables are defined simply by adding
  1642.  
  1643.     varname = value
  1644.  
  1645. lines to the configuration file before using
  1646.  
  1647.     ${varname}
  1648.  
  1649. afterwards to recall the assigned values. Here's an example:
  1650.  
  1651.     layout_class   = Log::Log4perl::Layout::PatternLayout
  1652.     layout_pattern = %d %F{1} %L> %m %n
  1653.     
  1654.     log4perl.category.Bar.Twix = WARN, Logfile, Screen
  1655.  
  1656.     log4perl.appender.Logfile  = Log::Log4perl::Appender::File
  1657.     log4perl.appender.Logfile.filename = test.log
  1658.     log4perl.appender.Logfile.layout = ${layout_class}
  1659.     log4perl.appender.Logfile.layout.ConversionPattern = ${layout_pattern}
  1660.  
  1661.     log4perl.appender.Screen  = Log::Log4perl::Appender::Screen
  1662.     log4perl.appender.Screen.layout = ${layout_class}
  1663.     log4perl.appender.Screen.layout.ConversionPattern = ${layout_pattern}
  1664.  
  1665. This is a convenient way to define two appenders with the same layout 
  1666. without having to retype the pattern definitions.
  1667.  
  1668. Variable substitution via C<${varname}> 
  1669. will first try to find an explicitely defined 
  1670. variable. If that fails, it will check your shell's environment
  1671. for a variable of that name. If that also fails, the program will C<die()>.
  1672.  
  1673. =head2 Perl Hooks in the Configuration File
  1674.  
  1675. If some of the values used in the Log4perl configuration file 
  1676. need to be dynamically modified by the program, use Perl hooks:
  1677.  
  1678.     log4perl.appender.File.filename = \
  1679.         sub { return getLogfileName(); }
  1680.  
  1681. Each value starting with the string C<sub {...> is interpreted as Perl code to
  1682. be executed at the time the application parses the configuration
  1683. via C<Log::Log4perl::init()>. The return value of the subroutine
  1684. is used by Log::Log4perl as the configuration value.
  1685.  
  1686. The Perl code is executed in the C<main> package, functions in
  1687. other packages have to be called in fully-qualified notation.
  1688.  
  1689. Here's another example, utilizing an environment variable as a
  1690. username for a DBI appender:
  1691.  
  1692.     log4perl.appender.DB.username = \
  1693.         sub { $ENV{DB_USER_NAME } }
  1694.  
  1695. However, please note the difference between these code snippets and those
  1696. used for user-defined conversion specifiers as discussed in
  1697. L<Log::Log4perl::Layout::PatternLayout>: 
  1698. While the snippets above are run I<once>
  1699. when C<Log::Log4perl::init()> is called, the conversion specifier
  1700. snippets are executed I<each time> a message is rendered according to
  1701. the PatternLayout.
  1702.  
  1703. SECURITY NOTE: this feature means arbitrary perl code can be embedded in the 
  1704. config file.  In the rare case where the people who have access to your config 
  1705. file are different from the people who write your code and shouldn't have 
  1706. execute rights, you might want to set
  1707.  
  1708.     Log::Log4perl::Config->allow_code(0);
  1709.  
  1710. before you call init().  Alternatively you can supply a restricted set of
  1711. Perl opcodes that can be embedded in the config file as described in
  1712. L<"Restricting what Opcodes can be in a Perl Hook">.
  1713.  
  1714. =head2 Restricting what Opcodes can be in a Perl Hook
  1715.  
  1716. The value you pass to Log::Log4perl::Config->allow_code() determines whether
  1717. the code that is embedded in the config file is eval'd unrestricted, or
  1718. eval'd in a Safe compartment.  By default, a value of '1' is assumed,
  1719. which does a normal 'eval' without any restrictions. A value of '0' 
  1720. however prevents any embedded code from being evaluated.
  1721.  
  1722. If you would like fine-grained control over what can and cannot be included
  1723. in embedded code, then please utilize the following methods:
  1724.  
  1725.  Log::Log4perl::Config->allow_code( $allow );
  1726.  Log::Log4perl::Config->allowed_code_ops($op1, $op2, ... );
  1727.  Log::Log4perl::Config->vars_shared_with_safe_compartment( [ \%vars | $package, \@vars ] );
  1728.  Log::Log4perl::Config->allowed_code_ops_convenience_map( [ \%map | $name, \@mask ] );
  1729.  
  1730. Log::Log4perl::Config-E<gt>allowed_code_ops() takes a list of opcode masks
  1731. that are allowed to run in the compartment.  The opcode masks must be
  1732. specified as described in L<Opcode>:
  1733.  
  1734.  Log::Log4perl::Config->allowed_code_ops(':subprocess');
  1735.  
  1736. This example would allow Perl operations like backticks, system, fork, and
  1737. waitpid to be executed in the compartment.  Of course, you probably don't
  1738. want to use this mask -- it would allow exactly what the Safe compartment is
  1739. designed to prevent.
  1740.  
  1741. Log::Log4perl::Config-E<gt>vars_shared_with_safe_compartment() 
  1742. takes the symbols which
  1743. should be exported into the Safe compartment before the code is evaluated. 
  1744. The keys of this hash are the package names that the symbols are in, and the
  1745. values are array references to the literal symbol names.  For convenience,
  1746. the default settings export the '%ENV' hash from the 'main' package into the
  1747. compartment:
  1748.  
  1749.  Log::Log4perl::Config->vars_shared_with_safe_compartment(
  1750.    main => [ '%ENV' ],
  1751.  );
  1752.  
  1753. Log::Log4perl::Config-E<gt>allowed_code_ops_convenience_map() is an accessor
  1754. method to a map of convenience names to opcode masks. At present, the
  1755. following convenience names are defined:
  1756.  
  1757.  safe        = [ ':browse' ]
  1758.  restrictive = [ ':default' ]
  1759.  
  1760. For convenience, if Log::Log4perl::Config-E<gt>allow_code() is called with a
  1761. value which is a key of the map previously defined with
  1762. Log::Log4perl::Config-E<gt>allowed_code_ops_convenience_map(), then the
  1763. allowed opcodes are set according to the value defined in the map. If this
  1764. is confusing, consider the following:
  1765.  
  1766.  use Log::Log4perl;
  1767.  
  1768.  my $config = <<'END';
  1769.   log4perl.logger = INFO, Main
  1770.   log4perl.appender.Main = Log::Log4perl::Appender::File
  1771.   log4perl.appender.Main.filename = \
  1772.       sub { "example" . getpwuid($<) . ".log" }
  1773.   log4perl.appender.Main.layout = Log::Log4perl::Layout::SimpleLayout
  1774.  END
  1775.  
  1776.  $Log::Log4perl::Config->allow_code('restrictive');
  1777.  Log::Log4perl->init( \$config );       # will fail
  1778.  $Log::Log4perl::Config->allow_code('safe');
  1779.  Log::Log4perl->init( \$config );       # will succeed
  1780.  
  1781. The reason that the first call to -E<gt>init() fails is because the
  1782. 'restrictive' name maps to an opcode mask of ':default'.  getpwuid() is not
  1783. part of ':default', so -E<gt>init() fails.  The 'safe' name maps to an opcode
  1784. mask of ':browse', which allows getpwuid() to run, so -E<gt>init() succeeds.
  1785.  
  1786. allowed_code_ops_convenience_map() can be invoked in several ways:
  1787.  
  1788. =over 4
  1789.  
  1790. =item allowed_code_ops_convenience_map()
  1791.  
  1792. Returns the entire convenience name map as a hash reference in scalar
  1793. context or a hash in list context.
  1794.  
  1795. =item allowed_code_ops_convenience_map( \%map )
  1796.  
  1797. Replaces the entire conveniece name map with the supplied hash reference.
  1798.  
  1799. =item allowed_code_ops_convenience_map( $name )
  1800.  
  1801. Returns the opcode mask for the given convenience name, or undef if no such
  1802. name is defined in the map.
  1803.  
  1804. =item allowed_code_ops_convenience_map( $name, \@mask )
  1805.  
  1806. Adds the given name/mask pair to the convenience name map.  If the name
  1807. already exists in the map, it's value is replaced with the new mask.
  1808.  
  1809. =back 
  1810.  
  1811. as can vars_shared_with_safe_compartment():
  1812.  
  1813. =over 4
  1814.  
  1815. =item vars_shared_with_safe_compartment()
  1816.  
  1817. Return the entire map of packages to variables as a hash reference in scalar
  1818. context or a hash in list context.
  1819.  
  1820. =item vars_shared_with_safe_compartment( \%packages )
  1821.  
  1822. Replaces the entire map of packages to variables with the supplied hash
  1823. reference.
  1824.  
  1825. =item vars_shared_with_safe_compartment( $package )
  1826.  
  1827. Returns the arrayref of variables to be shared for a specific package.
  1828.  
  1829. =item vars_shared_with_safe_compartment( $package, \@vars )
  1830.  
  1831. Adds the given package / varlist pair to the map.  If the package already
  1832. exists in the map, it's value is replaced with the new arrayref of variable
  1833. names.
  1834.  
  1835. =back
  1836.  
  1837. For more information on opcodes and Safe Compartments, see L<Opcode> and
  1838. L<Safe>.
  1839.  
  1840. =head2 Changing the Log Level on a Logger
  1841.  
  1842. Log4perl provides some internal functions for quickly adjusting the
  1843. log level from within a running Perl program. 
  1844.  
  1845. Now, some people might
  1846. argue that you should adjust your levels from within an external 
  1847. Log4perl configuration file, but Log4perl is everybody's darling.
  1848.  
  1849. Typically run-time adjusting of levels is done
  1850. at the beginning, or in response to some external input (like a
  1851. "more logging" runtime command for diagnostics).
  1852.  
  1853. You get the log level from a logger object with:
  1854.  
  1855.     $current_level = $logger->level();
  1856.  
  1857. and you may set it with the same method, provided you first
  1858. imported the log level constants, with:
  1859.  
  1860.     use Log::Log4perl::Level;
  1861.  
  1862. Then you can set the level on a logger to one of the constants,
  1863.  
  1864.     $logger->level($ERROR); # one of DEBUG, INFO, WARN, ERROR, FATAL
  1865.  
  1866. To B<increase> the level of logging currently being done, use:
  1867.  
  1868.     $logger->more_logging($delta);
  1869.  
  1870. and to B<decrease> it, use:
  1871.  
  1872.     $logger->less_logging($delta);
  1873.  
  1874. $delta must be a positive integer (for now, we may fix this later ;).
  1875.  
  1876. There are also two equivalent functions:
  1877.  
  1878.     $logger->inc_level($delta);
  1879.     $logger->dec_level($delta);
  1880.  
  1881. They're included to allow you a choice in readability. Some folks
  1882. will prefer more/less_logging, as they're fairly clear in what they
  1883. do, and allow the programmer not to worry too much about what a Level
  1884. is and whether a higher Level means more or less logging. However,
  1885. other folks who do understand and have lots of code that deals with
  1886. levels will probably prefer the inc_level() and dec_level() methods as
  1887. they want to work with Levels and not worry about whether that means
  1888. more or less logging. :)
  1889.  
  1890. That diatribe aside, typically you'll use more_logging() or inc_level()
  1891. as such:
  1892.  
  1893.     my $v = 0; # default level of verbosity.
  1894.     
  1895.     GetOptions("v+" => \$v, ...);
  1896.  
  1897.     $logger->more_logging($v);  # inc logging level once for each -v in ARGV
  1898.  
  1899. =head2 Custom Log Levels
  1900.  
  1901. First off, let me tell you that creating custom levels is heavily
  1902. deprecated by the log4j folks. Indeed, instead of creating additional
  1903. levels on top of the predefined DEBUG, INFO, WARN, ERROR and FATAL, 
  1904. you should use categories to control the amount of logging smartly,
  1905. based on the location of the log-active code in the system.
  1906.  
  1907. Nevertheless, 
  1908. Log4perl provides a nice way to create custom levels via the 
  1909. create_custom_level() routine function. However, this must be done
  1910. before the first call to init() or get_logger(). Say you want to create
  1911. a NOTIFY logging level that comes after WARN (and thus before INFO).
  1912. You'd do such as follows:
  1913.  
  1914.     use Log::Log4perl;
  1915.     use Log::Log4perl::Level;
  1916.  
  1917.     Log::Log4perl::Logger::create_custom_level("NOTIFY", "WARN");
  1918.  
  1919. And that's it! create_custom_level() creates the following functions /
  1920. variables for level FOO:
  1921.  
  1922.     $FOO_INT        # integer to use in L4p::Level::to_level()
  1923.     $logger->foo()  # log function to log if level = FOO
  1924.     $logger->is_foo()   # true if current level is >= FOO
  1925.  
  1926. These levels can also be used in your
  1927. config file, but note that your config file probably won't be
  1928. portable to another log4perl or log4j environment unless you've
  1929. made the appropriate mods there too.
  1930.  
  1931. =head2 System-wide log levels
  1932.  
  1933. As a fairly drastic measure to decrease (or increase) the logging level
  1934. all over the system with one single configuration option, use the C<threshold>
  1935. keyword in the Log4perl configuration file:
  1936.  
  1937.     log4perl.threshold = ERROR
  1938.  
  1939. sets the system-wide (or hierarchy-wide according to the log4j documentation)
  1940. to ERROR and therefore deprives every logger in the system of the right 
  1941. to log lower-prio messages.
  1942.  
  1943. =head2 Easy Mode
  1944.  
  1945. For teaching purposes (especially for [1]), I've put C<:easy> mode into 
  1946. C<Log::Log4perl>, which just initializes a single root logger with a 
  1947. defined priority and a screen appender including some nice standard layout:
  1948.  
  1949.     ### Initialization Section
  1950.     use Log::Log4perl qw(:easy);
  1951.     Log::Log4perl->easy_init($ERROR);  # Set priority of root logger to ERROR
  1952.  
  1953.     ### Application Section
  1954.     my $logger = get_logger();
  1955.     $logger->fatal("This will get logged.");
  1956.     $logger->debug("This won't.");
  1957.  
  1958. This will dump something like
  1959.  
  1960.     2002/08/04 11:43:09 ERROR> script.pl:16 main::function - This will get logged.
  1961.  
  1962. to the screen. While this has been proven to work well familiarizing people
  1963. with C<Log::Logperl> slowly, effectively avoiding to clobber them over the 
  1964. head with a 
  1965. plethora of different knobs to fiddle with (categories, appenders, levels, 
  1966. layout), the overall mission of C<Log::Log4perl> is to let people use
  1967. categories right from the start to get used to the concept. So, let's keep
  1968. this one fairly hidden in the man page (congrats on reading this far :).
  1969.  
  1970. =head2 Stealth loggers
  1971.  
  1972. Sometimes, people are lazy. If you're whipping up a 50-line script and want 
  1973. the comfort of Log::Log4perl without having the burden of carrying a
  1974. separate log4perl.conf file or a 5-liner defining that you want to append
  1975. your log statements to a file, you can use the following features:
  1976.  
  1977.     use Log::Log4perl qw(:easy);
  1978.  
  1979.     Log::Log4perl->easy_init( { level   => $DEBUG,
  1980.                                 file    => ">>test.log" } );
  1981.  
  1982.         # Logs to test.log via stealth logger
  1983.     DEBUG("Debug this!");
  1984.     INFO("Info this!");
  1985.     WARN("Warn this!");
  1986.     ERROR("Error this!");
  1987.  
  1988.     some_function();
  1989.  
  1990.     sub some_function {
  1991.             # Same here
  1992.         FATAL("Fatal this!");
  1993.     }
  1994.  
  1995. In C<:easy> mode, C<Log::Log4perl> will instantiate a I<stealth logger>
  1996. named C<$_default_logger> and import it into the current package. Also,
  1997. it will introduce the
  1998. convenience functions C<TRACE>, C<DEBUG()>, C<INFO()>, C<WARN()>, 
  1999. C<ERROR()>, C<FATAL()>, and C<ALWAYS> into the package namespace.
  2000. These functions simply take messages as
  2001. arguments and forward them to C<_default_logger-E<gt>debug()>,
  2002. C<_default_logger-E<gt>info()> and so on.
  2003. If a message should never be blocked, regardless of the log level,
  2004. use the C<ALWAYS> function which corresponds to a log level of C<OFF>:
  2005.  
  2006.     ALWAYS "This will be printed regardless of the log level";
  2007.  
  2008. The C<easy_init> method can be called with a single level value to
  2009. create a STDERR appender and a root logger as in
  2010.  
  2011.     Log::Log4perl->easy_init($DEBUG);
  2012.  
  2013. or, as shown below (and in the example above) 
  2014. with a reference to a hash, specifying values
  2015. for C<level> (the logger's priority), C<file> (the appender's data sink),
  2016. C<category> (the logger's category> and C<layout> for the appender's 
  2017. pattern layout specification.
  2018. All key-value pairs are optional, they 
  2019. default to C<$DEBUG> for C<level>, C<STDERR> for C<file>,
  2020. C<""> (root category) for C<category> and 
  2021. C<%d %m%n> for C<layout>:
  2022.  
  2023.     Log::Log4perl->easy_init( { level    => $DEBUG,
  2024.                                 file     => ">test.log",
  2025.                                 utf8     => 1,
  2026.                                 category => "Bar::Twix",
  2027.                                 layout   => '%F{1}-%L-%M: %m%n' } );
  2028.  
  2029. The C<file> parameter takes file names preceded by C<"E<gt>">
  2030. (overwrite) and C<"E<gt>E<gt>"> (append) as arguments. This will
  2031. cause C<Log::Log4perl::Appender::File> appenders to be created behind
  2032. the scenes. Also the keywords C<STDOUT> and C<STDERR> (no C<E<gt>> or
  2033. C<E<gt>E<gt>>) are recognized, which will utilize and configure
  2034. C<Log::Log4perl::Appender::Screen> appropriately. The C<utf8> flag,
  2035. if set to a true value, runs a C<binmode> command on the file handle
  2036. to establish a utf8 line discpline on the file, otherwise you'll get a
  2037. 'wide character in print' warning message and probably not what you'd
  2038. expect as output.
  2039.  
  2040. The stealth loggers can be used in different packages, you just need to make
  2041. sure you're calling the "use" function in every package you're using
  2042. C<Log::Log4perl>'s easy services:
  2043.  
  2044.     package Bar::Twix;
  2045.     use Log::Log4perl qw(:easy);
  2046.     sub eat { DEBUG("Twix mjam"); }
  2047.  
  2048.     package Bar::Mars;
  2049.     use Log::Log4perl qw(:easy);
  2050.     sub eat { INFO("Mars mjam"); }
  2051.  
  2052.     package main;
  2053.  
  2054.     use Log::Log4perl qw(:easy);
  2055.  
  2056.     Log::Log4perl->easy_init( { level    => $DEBUG,
  2057.                                 file     => ">>test.log",
  2058.                                 category => "Bar::Twix",
  2059.                                 layout   => '%F{1}-%L-%M: %m%n' },
  2060.                               { level    => $DEBUG,
  2061.                                 file     => "STDOUT",
  2062.                                 category => "Bar::Mars",
  2063.                                 layout   => '%m%n' },
  2064.                             );
  2065.     Bar::Twix::eat();
  2066.     Bar::Mars::eat();
  2067.  
  2068. As shown above, C<easy_init()> will take any number of different logger 
  2069. definitions as hash references.
  2070.  
  2071. Also, stealth loggers feature the functions C<LOGWARN()>, C<LOGDIE()>,
  2072. and C<LOGEXIT()>,
  2073. combining a logging request with a subsequent Perl warn() or die() or exit()
  2074. statement. So, for example
  2075.  
  2076.     if($all_is_lost) {
  2077.         LOGDIE("Terrible Problem");
  2078.     }
  2079.  
  2080. will log the message if the package's logger is at least C<FATAL> but
  2081. C<die()> (including the traditional output to STDERR) in any case afterwards.
  2082.  
  2083. See L<"Log and die or warn"> for the similar C<logdie()> and C<logwarn()>
  2084. functions of regular (i.e non-stealth) loggers.
  2085.  
  2086. Similarily, C<LOGCARP()>, C<LOGCLUCK()>, C<LOGCROAK()>, and C<LOGCONFESS()>
  2087. are provided in C<:easy> mode, facilitating the use of C<logcarp()>,
  2088. C<logcluck()>, C<logcroak()>, and C<logconfess()> with stealth loggers.
  2089.  
  2090. B<When using Log::Log4perl in easy mode, 
  2091. please make sure you understand the implications of 
  2092. L</"Pitfalls with Categories">>.
  2093.  
  2094. By the way, these convenience functions perform exactly as fast as the 
  2095. standard Log::Log4perl logger methods, there's I<no> performance penalty
  2096. whatsoever.
  2097.  
  2098. =head2 Nested Diagnostic Context (NDC)
  2099.  
  2100. If you find that your application could use a global (thread-specific)
  2101. data stack which your loggers throughout the system have easy access to,
  2102. use Nested Diagnostic Contexts (NDCs). Also check out
  2103. L<"Mapped Diagnostic Context (MDC)">, this might turn out to be even more
  2104. useful.
  2105.  
  2106. For example, when handling a request of a web client, it's probably 
  2107. useful to have the user's IP address available in all log statements
  2108. within code dealing with this particular request. Instead of passing
  2109. this piece of data around between your application functions, you can just
  2110. use the global (but thread-specific) NDC mechanism. It allows you
  2111. to push data pieces (scalars usually) onto its stack via
  2112.  
  2113.     Log::Log4perl::NDC->push("San");
  2114.     Log::Log4perl::NDC->push("Francisco");
  2115.  
  2116. and have your loggers retrieve them again via the "%x" placeholder in
  2117. the PatternLayout. With the stack values above and a PatternLayout format
  2118. like "%x %m%n", the call
  2119.  
  2120.     $logger->debug("rocks");
  2121.  
  2122. will end up as 
  2123.  
  2124.     San Francisco rocks
  2125.  
  2126. in the log appender.
  2127.  
  2128. The stack mechanism allows for nested structures.
  2129. Just make sure that at the end of the request, you either decrease the stack
  2130. one by one by calling
  2131.  
  2132.     Log::Log4perl::NDC->pop();
  2133.     Log::Log4perl::NDC->pop();
  2134.  
  2135. or clear out the entire NDC stack by calling
  2136.  
  2137.     Log::Log4perl::NDC->remove();
  2138.  
  2139. Even if you should forget to do that, C<Log::Log4perl> won't grow the stack
  2140. indefinitely, but limit it to a maximum, defined in C<Log::Log4perl::NDC>
  2141. (currently 5). A call to C<push()> on a full stack will just replace
  2142. the topmost element by the new value.
  2143.  
  2144. Again, the stack is always available via the "%x" placeholder
  2145. in the Log::Log4perl::Layout::PatternLayout class whenever a logger
  2146. fires. It will replace "%x" by the blank-separated list of the
  2147. values on the stack. It does that by just calling
  2148.  
  2149.     Log::Log4perl::NDC->get();
  2150.  
  2151. internally. See details on how this standard log4j feature is implemented
  2152. in L<Log::Log4perl::NDC>.
  2153.  
  2154. =head2 Mapped Diagnostic Context (MDC)
  2155.  
  2156. Just like the previously discussed NDC stores thread-specific
  2157. information in a stack structure, the MDC implements a hash table
  2158. to store key/value pairs in.
  2159.  
  2160. The static method
  2161.  
  2162.     Log::Log4perl::MDC->put($key, $value);
  2163.  
  2164. stores C<$value> under a key C<$key>, with which it can be retrieved later
  2165. (possibly in a totally different part of the system) by calling
  2166. the C<get> method:
  2167.  
  2168.     my $value = Log::Log4perl::MDC->get($key);
  2169.  
  2170. If no value has been stored previously under C<$key>, the C<get> method
  2171. will return C<undef>.
  2172.  
  2173. Typically, MDC values are retrieved later on via the C<"%X{...}"> placeholder
  2174. in C<Log::Log4perl::Layout::PatternLayout>. If the C<get()> method
  2175. returns C<undef>, the placeholder will expand to the string C<[undef]>.
  2176.  
  2177. An application taking a web request might store the remote host
  2178. like
  2179.  
  2180.     Log::Log4perl::MDC->put("remote_host", $r->headers("HOST"));
  2181.  
  2182. at its beginning and if the appender's layout looks something like
  2183.  
  2184.     log4perl.appender.Logfile.layout.ConversionPattern = %X{remote_host}: %m%n
  2185.  
  2186. then a log statement like
  2187.  
  2188.    DEBUG("Content delivered");
  2189.  
  2190. will log something like
  2191.  
  2192.    adsl-63.dsl.snf.pacbell.net: Content delivered 
  2193.  
  2194. later on in the program.
  2195.  
  2196. For details, please check L<Log::Log4perl::MDC>.
  2197.  
  2198. =head2 Resurrecting hidden Log4perl Statements
  2199.  
  2200. Sometimes scripts need to be deployed in environments without having
  2201. Log::Log4perl installed yet. On the other hand, you dont't want to
  2202. live without your Log4perl statements -- they're gonna come in
  2203. handy later.
  2204.  
  2205. So, just deploy your script with Log4perl statements commented out with the
  2206. pattern C<###l4p>, like in
  2207.  
  2208.     ###l4p DEBUG "It works!";
  2209.     # ...
  2210.     ###l4p INFO "Really!";
  2211.  
  2212. If Log::Log4perl is available,
  2213. use the C<:resurrect> tag to have Log4perl resurrect those burried 
  2214. statements before the script starts running:
  2215.  
  2216.     use Log::Log4perl qw(:resurrect :easy);
  2217.  
  2218.     ###l4p Log::Log4perl->easy_init($DEBUG);
  2219.     ###l4p DEBUG "It works!";
  2220.     # ...
  2221.     ###l4p INFO "Really!";
  2222.  
  2223. This will have a source filter kick in and indeed print
  2224.  
  2225.     2004/11/18 22:08:46 It works!
  2226.     2004/11/18 22:08:46 Really!
  2227.  
  2228. In environments lacking Log::Log4perl, just comment out the first line
  2229. and the script will run nevertheless (but of course without logging):
  2230.  
  2231.     # use Log::Log4perl qw(:resurrect :easy);
  2232.  
  2233.     ###l4p Log::Log4perl->easy_init($DEBUG);
  2234.     ###l4p DEBUG "It works!";
  2235.     # ...
  2236.     ###l4p INFO "Really!";
  2237.  
  2238. because everything's a regular comment now. Alternatively, put the
  2239. magic Log::Log4perl comment resurrection line into your shell's 
  2240. PERL5OPT environment variable, e.g. for bash:
  2241.  
  2242.     set PERL5OPT=-MLog::Log4perl=:resurrect,:easy
  2243.     export PERL5OPT
  2244.  
  2245. This will awaken the giant within an otherwise silent script like
  2246. the following:
  2247.  
  2248.     #!/usr/bin/perl
  2249.  
  2250.     ###l4p Log::Log4perl->easy_init($DEBUG);
  2251.     ###l4p DEBUG "It works!";
  2252.  
  2253. As of C<Log::Log4perl> 1.12, you can even force I<all> modules
  2254. loaded by a script to have their hidden Log4perl statements
  2255. resurrected. For this to happen, load C<Log::Log4perl::Resurrector>
  2256. I<before> loading any modules:
  2257.  
  2258.     use Log::Log4perl qw(:easy);
  2259.     use Log::Log4perl::Resurrector;
  2260.  
  2261.     use Foobar; # All hidden Log4perl statements in here will
  2262.                 # be uncommented before Foobar gets loaded.
  2263.  
  2264.     Log::Log4perl->easy_init($DEBUG);
  2265.     ...
  2266.  
  2267. Check the C<Log::Log4perl::Resurrector> manpage for more details.
  2268.  
  2269. =head2 Access defined appenders
  2270.  
  2271. All appenders defined in the configuration file or via Perl code
  2272. can be retrieved by the C<appender_by_name()> class method. This comes
  2273. in handy if you want to manipulate or query appender properties after
  2274. the Log4perl configuration has been loaded via C<init()>.
  2275.  
  2276. Note that internally, Log::Log4perl uses the C<Log::Log4perl::Appender> 
  2277. wrapper class to control the real appenders (like 
  2278. C<Log::Log4perl::Appender::File> or C<Log::Dispatch::FileRotate>). 
  2279. The C<Log::Log4perl::Appender> class has an C<appender> attribute,
  2280. pointing to the real appender.
  2281.  
  2282. The reason for this is that external appenders like 
  2283. C<Log::Dispatch::FileRotate> don't support all of Log::Log4perl's 
  2284. appender control mechanisms (like appender thresholds).
  2285.  
  2286. The previously mentioned method C<appender_by_name()> returns a
  2287. reference to the I<real> appender object. If you want access to the
  2288. wrapper class (e.g. if you want to modify the appender's threshold),
  2289. use the hash C<$Log::Log4perl::Logger::APPENDER_BY_NAME{...}> instead,
  2290. which holds references to all appender wrapper objects.
  2291.  
  2292. =head2 Modify appender thresholds
  2293.  
  2294. To conveniently adjust appender thresholds (e.g. because a script
  2295. uses more_logging()), use
  2296.  
  2297.        # decrease thresholds of all appenders
  2298.     Log::Log4perl->appender_thresholds_adjust(-1);
  2299.  
  2300. This will decrease the thresholds of all appenders in the system by
  2301. one level, i.e. WARN becomes INFO, INFO becomes DEBUG, etc. To only modify 
  2302. selected ones, use
  2303.  
  2304.        # decrease thresholds of all appenders
  2305.     Log::Log4perl->appender_thresholds_adjust(-1, ['AppName1', ...]);
  2306.  
  2307. and pass the names of affected appenders in a ref to an array.
  2308.  
  2309. =head1 Advanced configuration within Perl
  2310.  
  2311. Initializing Log::Log4perl can certainly also be done from within Perl.
  2312. At last, this is what C<Log::Log4perl::Config> does behind the scenes.
  2313. Log::Log4perl's configuration file parsers are using a publically 
  2314. available API to set up Log::Log4perl's categories, appenders and layouts.
  2315.  
  2316. Here's an example on how to configure two appenders with the same layout
  2317. in Perl, without using a configuration file at all:
  2318.  
  2319.   ########################
  2320.   # Initialization section
  2321.   ########################
  2322.   use Log::Log4perl;
  2323.   use Log::Log4perl::Layout;
  2324.   use Log::Log4perl::Level;
  2325.  
  2326.      # Define a category logger
  2327.   my $log = Log::Log4perl->get_logger("Foo::Bar");
  2328.  
  2329.      # Define a layout
  2330.   my $layout = Log::Log4perl::Layout::PatternLayout->new("[%r] %F %L %m%n");
  2331.  
  2332.      # Define a file appender
  2333.   my $file_appender = Log::Log4perl::Appender->new(
  2334.                           "Log::Log4perl::Appender::File",
  2335.                           name      => "filelog",
  2336.                           filename  => "/tmp/my.log");
  2337.  
  2338.      # Define a stdout appender
  2339.   my $stdout_appender =  Log::Log4perl::Appender->new(
  2340.                           "Log::Log4perl::Appender::Screen",
  2341.                           name      => "screenlog",
  2342.                           stderr    => 0);
  2343.  
  2344.      # Have both appenders use the same layout (could be different)
  2345.   $stdout_appender->layout($layout);
  2346.   $file_appender->layout($layout);
  2347.  
  2348.   $log->add_appender($stdout_appender);
  2349.   $log->add_appender($file_appender);
  2350.   $log->level($INFO);
  2351.  
  2352. Please note the class of the appender object is passed as a I<string> to
  2353. C<Log::Log4perl::Appender> in the I<first> argument. Behind the scenes,
  2354. C<Log::Log4perl::Appender> will create the necessary
  2355. C<Log::Log4perl::Appender::*> (or C<Log::Dispatch::*>) object and pass
  2356. along the name value pairs we provided to
  2357. C<Log::Log4perl::Appender-E<gt>new()> after the first argument.
  2358.  
  2359. The C<name> value is optional and if you don't provide one,
  2360. C<Log::Log4perl::Appender-E<gt>new()> will create a unique one for you.
  2361. The names and values of additional parameters are dependent on the requirements
  2362. of the particular appender class and can be looked up in their
  2363. manual pages.
  2364.  
  2365. A side note: In case you're wondering if
  2366. C<Log::Log4perl::Appender-E<gt>new()> will also take care of the
  2367. C<min_level> argument to the C<Log::Dispatch::*> constructors called
  2368. behind the scenes -- yes, it does. This is because we want the
  2369. C<Log::Dispatch> objects to blindly log everything we send them
  2370. (C<debug> is their lowest setting) because I<we> in C<Log::Log4perl>
  2371. want to call the shots and decide on when and what to log.
  2372.  
  2373. The call to the appender's I<layout()> method specifies the format (as a
  2374. previously created C<Log::Log4perl::Layout::PatternLayout> object) in which the
  2375. message is being logged in the specified appender. 
  2376. If you don't specify a layout, the logger will fall back to
  2377. C<Log::Log4perl::SimpleLayout>, which logs the debug level, a hyphen (-)
  2378. and the log message.
  2379.  
  2380. Layouts are objects, here's how you create them:
  2381.  
  2382.         # Create a simple layout
  2383.     my $simple = Log::Log4perl::SimpleLayout();
  2384.  
  2385.         # create a flexible layout:
  2386.         # ("yyyy/MM/dd hh:mm:ss (file:lineno)> message\n")
  2387.     my $pattern = Log::Log4perl::Layout::PatternLayout("%d (%F:%L)> %m%n");
  2388.  
  2389. Every appender has exactly one layout assigned to it. You assign
  2390. the layout to the appender using the appender's C<layout()> object:
  2391.  
  2392.     my $app =  Log::Log4perl::Appender->new(
  2393.                   "Log::Log4perl::Appender::Screen",
  2394.                   name      => "screenlog",
  2395.                   stderr    => 0);
  2396.  
  2397.         # Assign the previously defined flexible layout
  2398.     $app->layout($pattern);
  2399.  
  2400.         # Add the appender to a previously defined logger
  2401.     $logger->add_appender($app);
  2402.  
  2403.         # ... and you're good to go!
  2404.     $logger->debug("Blah");
  2405.         # => "2002/07/10 23:55:35 (test.pl:207)> Blah\n"
  2406.  
  2407. It's also possible to remove appenders from a logger:
  2408.  
  2409.     $logger->remove_appender($appender_name);
  2410.  
  2411. will remove an appender, specified by name, from a given logger. 
  2412. Please note that this does
  2413. I<not> remove an appender from the system.
  2414.  
  2415. To eradicate an appender from the system, 
  2416. you need to call C<Log::Log4perl-E<gt>eradicate_appender($appender_name)>
  2417. which will first remove the appender from every logger in the system
  2418. and then will delete all references Log4perl holds to it.
  2419.  
  2420. =head1 How about Log::Dispatch::Config?
  2421.  
  2422. Tatsuhiko Miyagawa's C<Log::Dispatch::Config> is a very clever 
  2423. simplified logger implementation, covering some of the I<log4j>
  2424. functionality. Among the things that 
  2425. C<Log::Log4perl> can but C<Log::Dispatch::Config> can't are:
  2426.  
  2427. =over 4
  2428.  
  2429. =item *
  2430.  
  2431. You can't assign categories to loggers. For small systems that's fine,
  2432. but if you can't turn off and on detailed logging in only a tiny
  2433. subsystem of your environment, you're missing out on a majorly
  2434. useful log4j feature.
  2435.  
  2436. =item *
  2437.  
  2438. Defining appender thresholds. Important if you want to solve problems like
  2439. "log all messages of level FATAL to STDERR, plus log all DEBUG
  2440. messages in C<Foo::Bar> to a log file". If you don't have appenders
  2441. thresholds, there's no way to prevent cluttering STDERR with DEBUG messages.
  2442.  
  2443. =item *
  2444.  
  2445. PatternLayout specifications in accordance with the standard
  2446. (e.g. "%d{HH:mm}").
  2447.  
  2448. =back
  2449.  
  2450. Bottom line: Log::Dispatch::Config is fine for small systems with
  2451. simple logging requirements. However, if you're
  2452. designing a system with lots of subsystems which you need to control
  2453. independantly, you'll love the features of C<Log::Log4perl>,
  2454. which is equally easy to use.
  2455.  
  2456. =head1 Using Log::Log4perl with wrapper functions and classes
  2457.  
  2458. If you don't use C<Log::Log4perl> as described above, 
  2459. but from a wrapper function, the pattern layout will generate wrong data 
  2460. for %F, %C, %L, and the like. Reason for this is that C<Log::Log4perl>'s 
  2461. loggers assume a static caller depth to the application that's using them. 
  2462.  
  2463. If you're using
  2464. one (or more) wrapper functions, C<Log::Log4perl> will indicate where
  2465. your logger function called the loggers, not where your application
  2466. called your wrapper:
  2467.  
  2468.     use Log::Log4perl qw(:easy);
  2469.     Log::Log4perl->easy_init({ level => $DEBUG, 
  2470.                                layout => "%M %m%n" });
  2471.  
  2472.     sub mylog {
  2473.         my($message) = @_;
  2474.  
  2475.         DEBUG $message;
  2476.     }
  2477.  
  2478.     sub func {
  2479.         mylog "Hello";
  2480.     }
  2481.  
  2482.     func();
  2483.  
  2484. prints
  2485.  
  2486.     main::mylog Hello
  2487.  
  2488. but that's probably not what your application expects. Rather, you'd
  2489. want
  2490.  
  2491.     main::func Hello
  2492.  
  2493. because the C<func> function called your logging function.
  2494.  
  2495. But don't dispair, there's a solution: Just register your wrapper
  2496. package with Log4perl beforehand. If Log4perl then finds that it's being 
  2497. called from a registered wrapper, it will automatically step up to the
  2498. next call frame.
  2499.  
  2500.     Log::Log4perl->wrapper_register(__PACKAGE__);
  2501.  
  2502.     sub mylog {
  2503.         my($message) = @_;
  2504.  
  2505.         DEBUG $message;
  2506.     }
  2507.  
  2508. Alternatively, you can increase the value of the global variable
  2509. C<$Log::Log4perl::caller_depth> (defaults to 0) by one for every
  2510. wrapper that's in between your application and C<Log::Log4perl>,
  2511. then C<Log::Log4perl> will compensate for the difference:
  2512.  
  2513.     sub mylog {
  2514.         my($message) = @_;
  2515.  
  2516.         local $Log::Log4perl::caller_depth =
  2517.               $Log::Log4perl::caller_depth + 1;
  2518.         DEBUG $message;
  2519.     }
  2520.  
  2521. Also, note that if you're writing a subclass of Log4perl, like
  2522.  
  2523.     package MyL4pWrapper;
  2524.     use Log::Log4perl;
  2525.     our @ISA = qw(Log::Log4perl);
  2526.  
  2527. and you want to call get_logger() in your code, like
  2528.  
  2529.     use MyL4pWrapper;
  2530.  
  2531.     sub get_logger {
  2532.         my $logger = Log::Log4perl->get_logger();
  2533.     }
  2534.  
  2535. then the get_logger() call will get a logger for the C<MyL4pWrapper>
  2536. category, not for the package calling the wrapper class as in
  2537.  
  2538.     package UserPackage;
  2539.     my $logger = MyL4pWrapper->get_logger();
  2540.  
  2541. To have the above call to get_logger return a logger for the 
  2542. "UserPackage" category, you need to tell Log4perl that "MyL4pWrapper"
  2543. is a Log4perl wrapper class:
  2544.  
  2545.     use MyL4pWrapper;
  2546.     Log::Log4perl->wrapper_register(__PACKAGE__);
  2547.  
  2548.     sub get_logger {
  2549.           # Now gets a logger for the category of the calling package
  2550.         my $logger = Log::Log4perl->get_logger();
  2551.     }
  2552.  
  2553. This feature works both for Log4perl-relaying classes like the wrapper
  2554. described above, and for wrappers that inherit from Log4perl use Log4perl's
  2555. get_logger function via inheritance, alike.
  2556.  
  2557. =head1 Access to Internals
  2558.  
  2559. The following methods are only of use if you want to peek/poke in
  2560. the internals of Log::Log4perl. Be careful not to disrupt its
  2561. inner workings.
  2562.  
  2563. =over 4
  2564.  
  2565. =item C<< Log::Log4perl->appenders() >>
  2566.  
  2567. To find out which appenders are currently defined (not only
  2568. for a particular logger, but overall), a C<appenders()>
  2569. method is available to return a reference to a hash mapping appender
  2570. names to their Log::Log4perl::Appender object references.
  2571.  
  2572. =back
  2573.  
  2574. =head1 Dirty Tricks
  2575.  
  2576. =over 4
  2577.  
  2578. =item infiltrate_lwp()
  2579.  
  2580. The famous LWP::UserAgent module isn't Log::Log4perl-enabled. Often, though,
  2581. especially when tracing Web-related problems, it would be helpful to get
  2582. some insight on what's happening inside LWP::UserAgent. Ideally, LWP::UserAgent
  2583. would even play along in the Log::Log4perl framework.
  2584.  
  2585. A call to C<Log::Log4perl-E<gt>infiltrate_lwp()> does exactly this. 
  2586. In a very rude way, it pulls the rug from under LWP::UserAgent and transforms
  2587. its C<debug/conn> messages into C<debug()> calls of loggers of the category
  2588. C<"LWP::UserAgent">. Similarily, C<LWP::UserAgent>'s C<trace> messages 
  2589. are turned into C<Log::Log4perl>'s C<info()> method calls. Note that this
  2590. only works for LWP::UserAgent versions E<lt> 5.822, because this (and
  2591. probably later) versions miss debugging functions entirely.
  2592.  
  2593. =item Suppressing 'duplicate' LOGDIE messages
  2594.  
  2595. If a script with a simple Log4perl configuration uses logdie() to catch
  2596. errors and stop processing, as in 
  2597.  
  2598.     use Log::Log4perl qw(:easy) ;
  2599.     Log::Log4perl->easy_init($DEBUG);
  2600.     
  2601.     shaky_function() or LOGDIE "It failed!";
  2602.  
  2603. there's a cosmetic problem: The message gets printed twice:
  2604.  
  2605.     2005/07/10 18:37:14 It failed!
  2606.     It failed! at ./t line 12
  2607.  
  2608. The obvious solution is to use LOGEXIT() instead of LOGDIE(), but there's
  2609. also a special tag for Log4perl that suppresses the second message:
  2610.  
  2611.     use Log::Log4perl qw(:no_extra_logdie_message);
  2612.  
  2613. This causes logdie() and logcroak() to call exit() instead of die(). To
  2614. modify the script exit code in these occasions, set the variable
  2615. C<$Log::Log4perl::LOGEXIT_CODE> to the desired value, the default is 1.
  2616.  
  2617. =item Redefine values without causing errors
  2618.  
  2619. Log4perl's configuration file parser has a few basic safety mechanisms to 
  2620. make sure configurations are more or less sane. 
  2621.  
  2622. One of these safety measures is catching redefined values. For example, if
  2623. you first write
  2624.  
  2625.     log4perl.category = WARN, Logfile
  2626.  
  2627. and then a couple of lines later
  2628.  
  2629.     log4perl.category = TRACE, Logfile
  2630.  
  2631. then you might have unintentionally overwritten the first value and Log4perl
  2632. will die on this with an error (suspicious configurations always throw an
  2633. error). Now, there's a chance that this is intentional, for example when
  2634. you're lumping together several configuration files and actually I<want>
  2635. the first value to overwrite the second. In this case use
  2636.  
  2637.     use Log::Log4perl qw(:nostrict);
  2638.  
  2639. to put Log4perl in a more permissive mode.
  2640.  
  2641. =back
  2642.  
  2643. =head1 EXAMPLE
  2644.  
  2645. A simple example to cut-and-paste and get started:
  2646.  
  2647.     use Log::Log4perl qw(get_logger);
  2648.     
  2649.     my $conf = q(
  2650.     log4perl.category.Bar.Twix         = WARN, Logfile
  2651.     log4perl.appender.Logfile          = Log::Log4perl::Appender::File
  2652.     log4perl.appender.Logfile.filename = test.log
  2653.     log4perl.appender.Logfile.layout = \
  2654.         Log::Log4perl::Layout::PatternLayout
  2655.     log4perl.appender.Logfile.layout.ConversionPattern = %d %F{1} %L> %m %n
  2656.     );
  2657.     
  2658.     Log::Log4perl::init(\$conf);
  2659.     
  2660.     my $logger = get_logger("Bar::Twix");
  2661.     $logger->error("Blah");
  2662.  
  2663. This will log something like
  2664.  
  2665.     2002/09/19 23:48:15 t1 25> Blah 
  2666.  
  2667. to the log file C<test.log>, which Log4perl will append to or 
  2668. create it if it doesn't exist already.
  2669.  
  2670. =head1 INSTALLATION
  2671.  
  2672. If you want to use external appenders provided with C<Log::Dispatch>,
  2673. you need to install C<Log::Dispatch> (2.00 or better) from CPAN,
  2674. which itself depends on C<Attribute-Handlers> and
  2675. C<Params-Validate>. And a lot of other modules, that's the reason
  2676. why we're now shipping Log::Log4perl with its own standard appenders
  2677. and only if you wish to use additional ones, you'll have to go through
  2678. the C<Log::Dispatch> installation process.
  2679.  
  2680. Log::Log4perl needs C<Test::More>, C<Test::Harness> and C<File::Spec>, 
  2681. but they already come with fairly recent versions of perl.
  2682. If not, everything's automatically fetched from CPAN if you're using the CPAN 
  2683. shell (CPAN.pm), because they're listed as dependencies.
  2684.  
  2685. C<Time::HiRes> (1.20 or better) is required only if you need the
  2686. fine-grained time stamps of the C<%r> parameter in
  2687. C<Log::Log4perl::Layout::PatternLayout>.
  2688.  
  2689. Manual installation works as usual with
  2690.  
  2691.     perl Makefile.PL
  2692.     make
  2693.     make test
  2694.     make install
  2695.  
  2696. If you're running B<Windows (98, 2000, NT, XP etc.)>, 
  2697. and you're too lazy to rummage through all of 
  2698. Log-Log4perl's dependencies, don't despair: We're providing a PPM package
  2699. which installs easily with your Activestate Perl. Check
  2700. L<Log::Log4perl::FAQ/"how_can_i_install_log__log4perl_on_microsoft_windows">
  2701. for details.
  2702.  
  2703. =head1 DEVELOPMENT
  2704.  
  2705. Log::Log4perl is still being actively developed. We will
  2706. always make sure the test suite (approx. 500 cases) will pass, but there 
  2707. might still be bugs. please check http://github.com/mschilli/log4perl
  2708. for the latest release. The api has reached a mature state, we will 
  2709. not change it unless for a good reason.
  2710.  
  2711. Bug reports and feedback are always welcome, just email them to our 
  2712. mailing list shown in the AUTHORS section. We're usually addressing
  2713. them immediately.
  2714.  
  2715. =head1 REFERENCES
  2716.  
  2717. =over 4
  2718.  
  2719. =item [1]
  2720.  
  2721. Michael Schilli, "Retire your debugger, log smartly with Log::Log4perl!",
  2722. Tutorial on perl.com, 09/2002, 
  2723. http://www.perl.com/pub/a/2002/09/11/log4perl.html
  2724.  
  2725. =item [2]
  2726.  
  2727. Ceki G├╝lc├╝, "Short introduction to log4j",
  2728. http://jakarta.apache.org/log4j/docs/manual.html
  2729.  
  2730. =item [3]
  2731.  
  2732. Vipan Singla, "Don't Use System.out.println! Use Log4j.",
  2733. http://www.vipan.com/htdocs/log4jhelp.html
  2734.  
  2735. =item [4]
  2736.  
  2737. The Log::Log4perl project home page: http://log4perl.com
  2738.  
  2739. =back
  2740.  
  2741. =head1 SEE ALSO
  2742.  
  2743. L<Log::Log4perl::Config|Log::Log4perl::Config>,
  2744. L<Log::Log4perl::Appender|Log::Log4perl::Appender>,
  2745. L<Log::Log4perl::Layout::PatternLayout|Log::Log4perl::Layout::PatternLayout>,
  2746. L<Log::Log4perl::Layout::SimpleLayout|Log::Log4perl::Layout::SimpleLayout>,
  2747. L<Log::Log4perl::Level|Log::Log4perl::Level>,
  2748. L<Log::Log4perl::JavaMap|Log::Log4perl::JavaMap>
  2749. L<Log::Log4perl::NDC|Log::Log4perl::NDC>,
  2750.  
  2751. =head1 AUTHORS
  2752.  
  2753. Please contribute patches to the project page on Github:
  2754.  
  2755.     http://github.com/mschilli/log4perl
  2756.  
  2757. Bug reports or requests for enhancements to the authors via 
  2758. our
  2759.  
  2760.     MAILING LIST (questions, bug reports, suggestions/patches): 
  2761.     log4perl-devel@lists.sourceforge.net
  2762.  
  2763.     Authors (please contact them via the list above, not directly)
  2764.     Mike Schilli <m@perlmeister.com>
  2765.     Kevin Goess <cpan@goess.org>
  2766.  
  2767.     Contributors (in alphabetical order):
  2768.     Ateeq Altaf, Cory Bennett, Jens Berthold, Jeremy Bopp, Hutton
  2769.     Davidson, Chris R. Donnelly, Matisse Enzer, Hugh Esco, Anthony
  2770.     Foiani, James FitzGibbon, Carl Franks, Dennis Gregorovic, Andy
  2771.     Grundman, Paul Harrington, David Hull, Robert Jacobson, Jason Kohles, 
  2772.     Jeff Macdonald, Markus Peter, Brett Rann, Peter Rabbitson, Erik
  2773.     Selberg, Aaron Straup Cope, Lars Thegler, David Viner, Mac Yang.
  2774.  
  2775. =head1 COPYRIGHT AND LICENSE
  2776.  
  2777. Copyright 2002-2009 by Mike Schilli E<lt>m@perlmeister.comE<gt> 
  2778. and Kevin Goess E<lt>cpan@goess.orgE<gt>.
  2779.  
  2780. This library is free software; you can redistribute it and/or modify
  2781. it under the same terms as Perl itself. 
  2782.  
  2783. =cut
  2784.